From 7577c9c888bd1c79edfc946ddd8e63984915d2bd Mon Sep 17 00:00:00 2001 From: Vishnu Narayanan Date: Thu, 24 Mar 2022 13:33:15 +0530 Subject: [PATCH] fix: drop conv and campaign seq on account delete (#4256) Conversation and campaign sequences persist in the database even after the related account is deleted. This PR adds an after_desttory callback on the account model that will delete the associated sequences. Fixes: #4252 --- app/models/account.rb | 6 ++++++ spec/models/account_spec.rb | 10 ++++++++++ 2 files changed, 16 insertions(+) diff --git a/app/models/account.rb b/app/models/account.rb index ee595902a..be081767c 100644 --- a/app/models/account.rb +++ b/app/models/account.rb @@ -79,6 +79,7 @@ class Account < ApplicationRecord before_validation :validate_limit_keys after_create_commit :notify_creation + after_destroy :remove_account_sequences def agents users.where(account_users: { role: :agent }) @@ -137,4 +138,9 @@ class Account < ApplicationRecord def validate_limit_keys # method overridden in enterprise module end + + def remove_account_sequences + ActiveRecord::Base.connection.exec_query("drop sequence IF EXISTS camp_dpid_seq_#{id}") + ActiveRecord::Base.connection.exec_query("drop sequence IF EXISTS conv_dpid_seq_#{id}") + end end diff --git a/spec/models/account_spec.rb b/spec/models/account_spec.rb index bd835865b..ff5f9cca5 100644 --- a/spec/models/account_spec.rb +++ b/spec/models/account_spec.rb @@ -30,4 +30,14 @@ RSpec.describe Account do expect(account.usage_limits).to eq({ agents: ChatwootApp.max_limit, inboxes: ChatwootApp.max_limit }) end end + + context 'when after_destroy is called' do + it 'conv_dpid_seq and camp_dpid_seq_ are deleted' do + account = create(:account) + query = "select * from information_schema.sequences where sequence_name in ('camp_dpid_seq_#{account.id}', 'conv_dpid_seq_#{account.id}');" + expect(ActiveRecord::Base.connection.execute(query).count).to eq(2) + account.destroy + expect(ActiveRecord::Base.connection.execute(query).count).to eq(0) + end + end end