This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'active_record/fixtures' | |
namespace :data do | |
# pipe separated values and yaml for now | |
EXTENSIONS = ['psv', 'yml'] | |
desc 'Truncate and load tables with seed data' | |
task :seed => :environment do | |
EXTENSIONS.each do |ext| | |
Dir[File.join(Rails.root, "db/seed/*.#{ext}")].each do |filename| | |
table_name = File.basename(filename, ".#{ext}") | |
sql = "TRUNCATE TABLE #{table_name};" | |
puts sql | |
ActiveRecord::Base.connection.execute(sql) | |
send(:"load_#{ext}", filename, table_name) | |
end | |
end | |
end | |
def load_psv(filename, table_name) | |
sql = %Q{ | |
LOAD DATA INFILE '#{filename}' | |
INTO TABLE #{table_name} FIELDS TERMINATED BY '|'; | |
} | |
puts sql | |
ActiveRecord::Base.connection.execute(sql) | |
end | |
def load_yml(filename, table_name) | |
Fixtures.create_fixtures('db/seed', table_name) | |
end | |
end |
One thing to look at carefully when using this technique is what your database product does with "empty" values in your data set. MySQL didn't want to seem to let a empty numeric value be NULL which caused me to go with some data massaging before and / or after load.