Skip to content

Commit

Permalink
Refactor and move the task
Browse files Browse the repository at this point in the history
  • Loading branch information
mayorova committed Aug 16, 2024
1 parent c5cb640 commit ee9e0a8
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 32 deletions.
32 changes: 0 additions & 32 deletions lib/tasks/database_cleanup.rake

This file was deleted.

31 changes: 31 additions & 0 deletions lib/tasks/multitenant/tenants.rake
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,37 @@ namespace :multitenant do
update_tenant_ids(proc { |object| object.account.tenant_id }, proc { account }, proc { tenant_id == nil }, args.to_hash.merge({ table_name: 'Alert' }))
end

desc 'Check and remove orphaned objects (whose tenant is missing), pass "destroy" argument to delete'
task :cleanup_orphans, [:mode] => :environment do |_task, args|
puts 'Checking and removing orphaned objects...'

destroy = args[:mode] == "destroy"

puts "WARNING: the found orphan objects will be destroyed" if destroy

provider_account_ids = Account.where(provider: true).pluck(:id) + [Account.master.id]

ApplicationRecord.descendants.each do |model|
next unless model.table_exists? && model.column_names.include?('tenant_id')

orphaned_objects = model.where.not(tenant_id: provider_account_ids)

if orphaned_objects.exists?
puts "Found orphaned objects in #{model.table_name}:"
orphaned_objects.find_each { |obj| puts "- ID: #{obj.id}, Tenant ID: #{obj.tenant_id}" }

if destroy
puts "Destroying orphan #{model.table_name}..."
orphaned_objects.in_batches(of: 100).destroy_all
end
else
puts "No orphaned objects found in #{model.table_name}."
end
end

puts 'Orphaned objects check completed.'
end

def update_tenant_ids(tenant_id_block, association_block, condition, **args)
query = args[:table_name].constantize.joining(&association_block).where.has(&condition)
puts "------ Updating #{args[:table_name]} ------"
Expand Down

0 comments on commit ee9e0a8

Please sign in to comment.