Dump db to fixtures (generate fixtures from db)
May 26th, 2006
This is a quite interesting thread on rails ml with the solution to my problem.
I wanted to generate fixtures automatically from my db. This is a rake action that does the job well. Just put it into lib/tasks/ and call it dump_fixtures.rake
desc 'Dump a database to yaml fixtures. Set environment variables DB
and DEST to specify the target database and destination path for the
fixtures. DB defaults to development and DEST defaults to RAILS_ROOT/
test/fixtures.'
task :dump_fixtures => :environment do
path = ENV['DEST'] || "#{RAILS_ROOT}/test/fixtures"
db = ENV['DB'] || 'development'
sql = 'SELECT * FROM %s'
ActiveRecord::Base.establish_connection(db)
ActiveRecord::Base.connection.select_values('show tables').each do |table_name|
i = '000'
File.open("#{path}/#{table_name}.yml", 'wb') do |file|
file.write ActiveRecord::Base.connection.select_all(sql %
table_name).inject({}) { |hash, record|
hash["#{table_name}_#{i.succ!}"] = record
hash
}.to_yaml
end
end
end
# ActiveRecord::Base.connection.select_values('show tables')
# is mysql specific
# SQLite: ActiveRecord::Base.connection.select_values('.table')
# Postgres
# table_names = ActiveRecord::Base.connection.select_values(<<-end_sql)
# SELECT c.relname
# FROM pg_class c
# LEFT JOIN pg_roles r ON r.oid = c.relowner
# LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
# WHERE c.relkind IN ('r','')
# AND n.nspname IN ('myappschema', 'public')
# AND pg_table_is_visible(c.oid)
# end_sql
2 Responses to “Dump db to fixtures (generate fixtures from db)”
1RiK0’s Tech Temple · Beautify Fixtures (Ruby on Rails)
June 14th, 2006 @ 18:01
[...] After generating fixtures from my development database (you can read about it here) I decided to make them nice. [...]
2Sergio Espeja
July 28th, 2008 @ 13:23
Very usefull rake task, I’ve found a little bug. It makes a fixture called schema_info.yml, in order to avoit it you can use:
…
ActiveRecord::Base.connection.select_values(’show tables’).each do |table_name|
next if table_name == “schema_info”
i = ‘000′
…
Thanks!
Leave a Reply