Skip to content

Commit

Permalink
Improvements for orphan objects removal
Browse files Browse the repository at this point in the history
  • Loading branch information
mayorova committed Oct 15, 2024
1 parent 9d228f9 commit 5a16d0a
Showing 1 changed file with 22 additions and 9 deletions.
31 changes: 22 additions & 9 deletions lib/tasks/multitenant/tenants.rake
Original file line number Diff line number Diff line change
Expand Up @@ -86,19 +86,21 @@ namespace :multitenant do

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')

base_models.each do |model|
orphaned_objects = model.where.not(tenant_id: provider_account_ids)

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

if destroy
puts "Destroying orphaned objects for model #{model.name}..."
orphaned_objects.in_batches(of: 100).destroy_all
puts "Found #{orphaned_objects.size} orphaned objects for model #{model.name}:"
orphaned_objects.find_in_batches(batch_size: 100).with_index do |batch, index|
puts "Processing batch #{index+1} of model #{model.name}..."
batch.each do |object|
puts "- ID: #{object.id}, Tenant ID: #{object.tenant_id}"
object.destroy if destroy
end
end
orphaned_objects.find_each { |obj| }


else
puts "No orphaned objects found for model #{model.name}."
end
Expand All @@ -107,6 +109,17 @@ namespace :multitenant do
puts 'Orphaned objects check completed.'
end

def base_models
all_models = ApplicationRecord.descendants.select(&:arel_table).reject(&:abstract_class?)
all_models.select! { _1.attribute_names.include? "tenant_id"}
# we only want base STI classes, not the children
all_models.select do |model|
base_class = model.base_class
# either current model is the base_class or we can't find a base class amongst the discovered models (which would be very weird)
base_class == model || all_models.none? { |potential_parent| potential_parent == base_class }
end
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 5a16d0a

Please sign in to comment.