Initially this question was marked as duplicate of: Postgres unique constraint vs index
but Im not asking the differences of unique constraint vs unique index, that's why I updated the question title to make it more clear.
I would like to know why adding a unique constraint that uses a unique index just removes the indices, let me explain in detail, I have the following migration:
class AddUniqueIndexOnNamesForProgramsSuppliersCollections < ActiveRecord::Migration[5.2]
disable_ddl_transaction!
def up
execute("CREATE UNIQUE INDEX CONCURRENTLY idx_supplier_company_id_and_name_unique ON public.suppliers USING btree (company_id, name);")
execute("CREATE UNIQUE INDEX CONCURRENTLY idx_programs_company_id_and_name_unique ON public.programs USING btree (company_id, name);")
execute("CREATE UNIQUE INDEX CONCURRENTLY idx_collections_supplier_id_and_name_unique ON public.collections USING btree (supplier_id, name);")
end
def down
remove_index :suppliers, name: :idx_supplier_company_id_and_name_unique
remove_index :programs, name: :idx_programs_company_id_and_name_unique
remove_index :collections, name: :idx_collections_supplier_id_and_name_unique
end
end
When I run the above migration I get the indices added to my structure.sql
file. Then I have this other migration:
class AddUniqueConstraintsOnNamesForProgramsSuppliersCollections < ActiveRecord::Migration[5.2]
disable_ddl_transaction!
def up
sql = <<~END_OF_SQL
ALTER TABLE public.suppliers ADD CONSTRAINT supplier_company_id_and_name_unique UNIQUE USING INDEX idx_supplier_company_id_and_name_unique;
ALTER TABLE public.programs ADD CONSTRAINT programs_company_id_and_name_unique UNIQUE USING INDEX idx_programs_company_id_and_name_unique;
ALTER TABLE public.collections ADD CONSTRAINT collections_supplier_id_and_name_unique UNIQUE USING INDEX idx_collections_supplier_id_and_name_unique;
END_OF_SQL
execute(sql)
end
def down
sql = <<~END_OF_SQL
ALTER TABLE public.suppliers DROP CONSTRAINT supplier_company_id_and_name_unique;
ALTER TABLE public.programs DROP CONSTRAINT programs_company_id_and_name_unique;
ALTER TABLE public.collections DROP CONSTRAINT collections_supplier_id_and_name_unique;
END_OF_SQL
execute(sql)
end
end
When I run the second migration indices get removed from my structure.sql
file and from my DB and adds the constraints instead, so my guess is that it is replacing the indices with the constraints but I would like to have both, any idea?