diff --git a/app/models/services/service_instance.rb b/app/models/services/service_instance.rb index 612b2e9bac8..6e5355b6a1e 100644 --- a/app/models/services/service_instance.rb +++ b/app/models/services/service_instance.rb @@ -24,7 +24,6 @@ class InvalidServiceBinding < StandardError; end serialize_attributes :json, :tags one_to_one :service_instance_operation - add_association_dependencies service_instance_operation: :destroy one_to_many :service_bindings, before_add: :validate_service_binding, key: :service_instance_guid, primary_key: :guid one_to_many :service_keys diff --git a/db/migrations/20220805145100_add_delete_on_cascade_to_fk_svc_inst_op_svc_instance_id.rb b/db/migrations/20220805145100_add_delete_on_cascade_to_fk_svc_inst_op_svc_instance_id.rb new file mode 100644 index 00000000000..c4409cb0646 --- /dev/null +++ b/db/migrations/20220805145100_add_delete_on_cascade_to_fk_svc_inst_op_svc_instance_id.rb @@ -0,0 +1,18 @@ +Sequel.migration do + # Add DELETE CASCADE to foreign key fk_svc_inst_op_svc_instance_id to ensure that 'service instance operations' + # are deleted together with the referenced 'service instance'. + + up do + alter_table :service_instance_operations do + drop_constraint :fk_svc_inst_op_svc_instance_id, type: :foreign_key + add_foreign_key [:service_instance_id], :service_instances, key: :id, name: :fk_svc_inst_op_svc_instance_id, on_delete: :cascade + end + end + + down do + alter_table :service_instance_operations do + drop_constraint :fk_svc_inst_op_svc_instance_id, type: :foreign_key + add_foreign_key [:service_instance_id], :service_instances, key: :id, name: :fk_svc_inst_op_svc_instance_id + end + end +end diff --git a/spec/unit/models/services/service_instance_spec.rb b/spec/unit/models/services/service_instance_spec.rb index 9a4ac055557..96b01a6d2c1 100644 --- a/spec/unit/models/services/service_instance_spec.rb +++ b/spec/unit/models/services/service_instance_spec.rb @@ -183,6 +183,16 @@ module VCAP::CloudController expect(ServiceInstanceAnnotationModel.where(id: annotation.id)).to be_empty end + it 'cascade deletes the related ServiceInstanceOperation for this instance' do + last_operation = ServiceInstanceOperation.make + service_instance.service_instance_operation = last_operation + + service_instance.destroy + + expect(ServiceInstance.find(id: service_instance.id)).to be_nil + expect(ServiceInstanceOperation.find(id: last_operation.id)).to be_nil + end + it 'creates a DELETED service usage event' do expect { service_instance.destroy