Skip to content

Instantly share code, notes, and snippets.

@Sudrien
Last active March 4, 2025 23:44
Show Gist options
  • Save Sudrien/2a6a1e4d1c46270232c4fc0ba7d5ea35 to your computer and use it in GitHub Desktop.
Save Sudrien/2a6a1e4d1c46270232c4fc0ba7d5ea35 to your computer and use it in GitHub Desktop.
When railties:install:migrations doesn't line up tith you pre-rails-7 database
# rake railties:install:migrations
# rake db:reschema_migrations
# rake db:migrate
#
# If you find you old database has a lot of schema_migrations.versions from the pre-rails 7 days
# this adds another entry for the new date assigned by railties:install:migrations
namespace :db do
desc 'add migration numbers for newly renamed Rails 7 migrations'
task reschema_migrations: :'db:load_config' do
if ENV["DATABASE"].present? && ENV["DATABASE"] != "primary"
config = ActiveRecord::Base.configurations.configs_for(name: ENV["DATABASE"])
raise "Invalid DATABASE provided" if config.blank?
destination = config.migrations_paths
raise "#{ENV["DATABASE"]} does not have a custom migration path" if destination.blank?
else
destination = ActiveRecord::Tasks::DatabaseTasks.migrations_paths.first
end
migration_conversions = {}
Dir.glob(File.join(destination, '*.rb')).each do |filename|
first_line = File.open(filename, 'r') { |f| f.readline.chomp.gsub(/[^0-9]/, '') }
migration_conversions[first_line] = filename.split(/\//).last.gsub(/[^0-9]/, '')
end
connection = ActiveRecord::Base.connection
migration_conversions.each do |migration_original, migration_rename|
connection.execute(%(
INSERT INTO schema_migrations (version)
SELECT '#{migration_rename}'
WHERE EXISTS (SELECT 1 FROM schema_migrations WHERE version = '#{migration_original}')
AND NOT EXISTS (SELECT 1 FROM schema_migrations WHERE version = '#{migration_rename}');
))
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment