如何在一次迁移中删除很多带有所有引用的表?

时间:2019-07-03 17:53:05

标签: ruby-on-rails postgresql rails-migrations

我需要从数据库中删除400个表中的150个。我想删除所有引用。最好的方法是什么?

我试图通过以下方式做到

class RemoveOldTables < ActiveRecord::Migration

  UNUSED_TABLES = %w[
    ...
  ].freeze

  def up
    foreign_keys = foreign_key_list.with_indifferent_access
    unused_existed_tables = UNUSED_TABLES & ActiveRecord::Base.connection.tables
    unused_existed_tables.each do |table|
      foreign_keys[table].each do |item|
        remove_column item[:table], item[:column_name], :integer
      end
      drop_table table, force: :cascade
    end
  end

  def foreign_key_list
    sql = <<-SQL
      select kcu.table_schema || '.' || kcu.table_name as foreign_table,
             '>-' as rel,
             rel_kcu.table_schema || '.' || rel_kcu.table_name as primary_table,
             kcu.ordinal_position as no,
             kcu.column_name as fk_column,
             '=' as join,
             rel_kcu.column_name as pk_column,
             kcu.constraint_name
      from information_schema.table_constraints tco
      join information_schema.key_column_usage kcu
                on tco.constraint_schema = kcu.constraint_schema
                and tco.constraint_name = kcu.constraint_name
      join information_schema.referential_constraints rco
                on tco.constraint_schema = rco.constraint_schema
                and tco.constraint_name = rco.constraint_name
      join information_schema.key_column_usage rel_kcu
                on rco.unique_constraint_schema = rel_kcu.constraint_schema
                and rco.unique_constraint_name = rel_kcu.constraint_name
                and kcu.ordinal_position = rel_kcu.ordinal_position
      where tco.constraint_type = 'FOREIGN KEY'
      order by kcu.table_schema,
               kcu.table_name,
               kcu.ordinal_position;
    SQL

    result = ActiveRecord::Base.connection.execute(sql)
    result.to_a.each_with_object({}) do |item, obj|
      foreign_table =item['foreign_table']
      primary_table = item['primary_table']

      obj[primary_table] ||= []
      obj[primary_table] << { table: foreign_table, column_name: item['fk_column'] }
    end
  end
end

但是我在删除其中一列时收到下一个错误:

  

PG :: DependentObjectsStillExist:错误:无法删除列   表course_lesson_plans的Academic_year_id,因为其他对象   取决于它详细信息:视图v_course_lesson_plans取决于列   表course_lesson_plans的Academic_year_id提示:使用DROP ...   CASCADE也删除依赖对象。 :更改表   “ course_lesson_plans” DROP“ academic_year_id”

如何循环删除所有表,所有外键,所有引用

0 个答案:

没有答案