Skip to content

Instantly share code, notes, and snippets.

@copiousfreetime
Forked from chad/exporter.rb
Created February 26, 2012 20:18
Show Gist options
  • Save copiousfreetime/1918794 to your computer and use it in GitHub Desktop.
Save copiousfreetime/1918794 to your computer and use it in GitHub Desktop.
Export ActiveRecord Tables to CSV
#!/usr/bin/env ruby
# Completely untested method to dump a set of postgres tables to CSV
require 'yaml'
export_tables = %w[ invoice invoice_item item merchant transaction user ]
destination_folder = 'tmp'
db_config_file = 'config/database.yml'
db = YAML.load( db_config_file )[:production]
export_tables.each do |table|
dest_file = File.join( destination_folder, "#{table}.csv" )
cmd = "PGPASS=#{db[:password]} psql --username #{db[:username]} --host #{db[:host]} -c 'COPY #{table} TO STDOUT WITH (FORMAT CSV, HEADER true )' > #{dest_file}"
puts "Dumping #{table} to #{dest_file}"
system( cmd )
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment