Ruby Sequel
Mon Jun 16th 2008, 5:02pm
Recently I needed to write a one-shot script to migrate data from one database to another, as my employer rolled out a new version of one of the company's internal software apps. Instead of just cranking out something in PHP, I decided to give Sequel a shot.

Sequel presents the database to you as if it were a nested set of arrays. My script was a bigger and only slightly more elaborate version of the following simple script:
sourcedb = 'postgres://user:pass@x.x.x.x/dbname'
destdb = 'postgres://user:pass@y.y.y.y/dbname'

destdb.transaction do


  sourcedb[:devicemodel].each do |row|

    # perform fixup/conversion here

    destdb[:devicemodel] << row

  # other tables here

The neat thing too is if you just want to run some SQL because you know exactly what you need to do, it's easy, and the results are returned to you in the same way that you can iterate over:
  emails = db["select distinct emailcontact from contact where accountkey in (select
distinct accountkey from contract)"].all

  emails.each do |row|
    next if row[:emailcontact].nil?
    puts row[:emailcontact]
For a more thorough introduction I'd read this interview with Sharon Rosner, the creator of Sequel, discussing why Sequel was born and where it's a good fit versus other existing ORM tools. For my migration script, it was great, allowing me to write simple Ruby loops manipulating the data as an array, yet allowing me to do raw SQL wherever it was easier.