Module: RailsSchemaCleaner

Defined in:
lib/rails_schema_cleaner.rb,
lib/rails_schema_cleaner/version.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

DEFAULT_TABLES =
["ar_internal_metadata", "schema_migrations"].to_set
VERSION =
"0.1.1"

Class Method Summary collapse

Class Method Details

.establish_db_connection!Object



40
41
42
43
44
45
46
47
48
49
# File 'lib/rails_schema_cleaner.rb', line 40

def self.establish_db_connection!
  require File.expand_path(Dir.pwd + "/config/environment", __FILE__)

  db_config = Rails.configuration.database_configuration[Rails.env]
  ActiveRecord::Base.establish_connection(db_config)

  Rails.application.eager_load!

  puts "Database connection established!"
end

.generate_migrationObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rails_schema_cleaner.rb', line 18

def self.generate_migration
  tables_to_drop = orphaned_tables
  return puts "No orphaned tables found." if tables_to_drop.empty?

  timestamp = Time.now.utc.strftime("%Y%m%d%H%M%S")
  migration_filename = "db/migrate/#{timestamp}_drop_orphaned_tables.rb"

  # Define the migration class with the correct format
  migration_class = "ActiveRecord::Migration[#{Rails::VERSION::MAJOR}.0]"

  migration_content = "    class DropOrphanedTables < \#{migration_class}\n      def change\n        \#{tables_to_drop.map { |t| \"drop_table :\#{t}\" }.join(\"\\n    \")}\n      end\n    end\n  RUBY\n\n  File.write(migration_filename, migration_content)\n  puts \"Migration created: \#{migration_filename}\"\nend\n"

.orphaned_tablesObject



10
11
12
13
14
15
16
# File 'lib/rails_schema_cleaner.rb', line 10

def self.orphaned_tables
  establish_db_connection! unless ActiveRecord::Base.connected?

  db_tables = ActiveRecord::Base.connection.tables.to_set
  model_tables = ActiveRecord::Base.descendants.map(&:table_name).compact.to_set
  db_tables - model_tables - DEFAULT_TABLES
end