2020-07-21 19:25:21 +02:00
|
|
|
# frozen_string_literal: false
|
|
|
|
|
|
|
|
namespace :db do
|
2023-03-23 17:39:06 +01:00
|
|
|
# Usage example:
|
|
|
|
# RAILS_ENV=test rails db:to_fixtures[chained_elements]
|
2020-07-21 19:25:21 +02:00
|
|
|
desc 'Convert development DB to Rails test fixtures'
|
2020-07-22 09:45:20 +02:00
|
|
|
task :to_fixtures, [:table] => :environment do |_task, args|
|
2023-03-22 17:30:37 +01:00
|
|
|
tables_to_skip = %w[ar_internal_metadata delayed_jobs schema_info schema_migrations].freeze
|
2020-07-21 19:25:21 +02:00
|
|
|
|
|
|
|
begin
|
|
|
|
ActiveRecord::Base.establish_connection
|
|
|
|
ActiveRecord::Base.connection.tables.each do |table_name|
|
2023-03-22 17:30:37 +01:00
|
|
|
next if tables_to_skip.include?(table_name)
|
2020-07-22 09:45:20 +02:00
|
|
|
next if args.table && args.table != table_name
|
2020-07-21 19:25:21 +02:00
|
|
|
|
2023-03-23 17:39:06 +01:00
|
|
|
counter = '000'
|
|
|
|
file_path = Rails.root.join("test/fixtures/#{table_name}.yml")
|
|
|
|
File.open(file_path, File::WRONLY | File::CREAT) do |file|
|
2020-07-21 19:25:21 +02:00
|
|
|
rows = ActiveRecord::Base.connection.select_all("SELECT * FROM #{table_name}")
|
|
|
|
data = rows.each_with_object({}) do |record, hash|
|
2023-03-23 17:39:06 +01:00
|
|
|
suffix = record['id'].presence || counter.succ!
|
|
|
|
# FIXME, this is broken with jsonb columns: it records a String but a Hash must be saved
|
|
|
|
hash["#{table_name.singularize}#{suffix}"] = record
|
2020-07-21 19:25:21 +02:00
|
|
|
end
|
|
|
|
puts "Writing table '#{table_name}' to '#{file_path}'"
|
|
|
|
file.write(data.to_yaml)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
ensure
|
|
|
|
ActiveRecord::Base.connection&.close
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|