Export to CSV

databases sequel heroku

Mon Mar 30 01:01:32 -0700 2009

A quick script to export a database table to CSV is below. Drop into lib/tasks/export.rake (Rails), or directly into your Rakefile, then call at the command line:

$ DATABASE_URL=sqlite://db/development.sqlite3 rake export table=users > users.csv

FasterCSV handles properly quotes everything, and Sequel gives easy access to the raw data. (Substitute your own database config as a url, or patch the script to read from config/database.yml if you prefer.)

Don’t use this on a huge table, since it reads the result set into memory. But it should be fine for the average small-to-medium sized dataset.

It will work on Heroku, too:

$ heroku rake export table=widgets > widgets.csv

The script: