chore: Automate conversation display_id generation with db triggers (#1412)

Automate conversation display_id generation with db triggers

Co-authored-by: Saurabh Mehta <saurabh1.mehta@airtel.com>
Co-authored-by: Sojan Jose <sojan@pepalo.com>
This commit is contained in:
Saurabh Mehta
2021-01-05 20:07:04 +05:30
committed by GitHub
parent 45059b6fe9
commit 627d3a575a
10 changed files with 102 additions and 18 deletions

View File

@@ -0,0 +1,27 @@
# This migration was auto-generated via `rake db:generate_trigger_migration'.
# While you can edit this file, any changes you make to the definitions here
# will be undone by the next auto-generated trigger migration.
class CreateTriggersAccountsInsertOrConversationsInsert < ActiveRecord::Migration[6.0]
def up
create_trigger('accounts_after_insert_row_tr', generated: true, compatibility: 1)
.on('accounts')
.after(:insert)
.for_each(:row) do
"execute format('create sequence IF NOT EXISTS conv_dpid_seq_%s', NEW.id);"
end
create_trigger('conversations_before_insert_row_tr', generated: true, compatibility: 1)
.on('conversations')
.before(:insert)
.for_each(:row) do
"NEW.display_id := nextval('conv_dpid_seq_' || NEW.account_id);"
end
end
def down
drop_trigger('accounts_after_insert_row_tr', 'accounts', generated: true)
drop_trigger('conversations_before_insert_row_tr', 'conversations', generated: true)
end
end

View File

@@ -0,0 +1,21 @@
class ConvDpidSeqForExistingAccnts < ActiveRecord::Migration[6.0]
def up
::Account.find_in_batches do |accounts_batch|
Rails.logger.info "migrated till #{accounts_batch.first.id}\n"
accounts_batch.each do |account|
display_id = Conversation.where(account_id: account.id).maximum('display_id')
display_id ||= 0 # for accounts with out conversations
ActiveRecord::Base.connection.exec_query("create sequence IF NOT EXISTS conv_dpid_seq_#{account.id} START #{display_id + 1}")
end
end
end
def down
::Account.find_in_batches do |accounts_batch|
Rails.logger.info "migrated till #{accounts_batch.first.id}\n"
accounts_batch.each do |account|
ActiveRecord::Base.connection.exec_query("drop sequence IF EXISTS conv_dpid_seq_#{account.id}")
end
end
end
end