views:

44

answers:

2

I'm running an import script which imports a CSV dump of a database into a local sqlite database using DataMapper.

My models look like this:

class Staff

    include DataMapper::Resource

    property  :staff_id, String, :key => true
    property  :full_name, String

end

class Project

  include DataMapper::Resource

  property  :project_id, Integer, :key => true
  property  :title, String
  property  :status, String

 belongs_to  :staff

end

The CSV contains the primary key so when I'm do the import I'm using that as it's key. Next time I run the import I clear the tables and start again, however datamapper moans because the primary keys have already been taken.

Is there a way to stop datamapper moaning about this or should I just delete the .db file and re-create an empty .db file just before the import runs? If so what's the easiest way to do this.

A: 

If you create the complete DB from the import, I'd really recommend nuking the database completely to avoid any spill-over from earlier runs. This also keeps your build-db code path well tested.

David Schmitt
Yea it's totally created from an CSV export, I won't be writing to it at all. So should I just remove the file and create it afresh each time? if so what's the best way to do that in Ruby?
Tom
+2  A: 

You can use DataMapper.auto_migrate! to blow away the tables, and then recreate them matching the current model state. The new tables will be empty of any data from previous runs.

So just after you define your models, but before you begin importing the data do something like the following:

DataMapper.finalize.auto_migrate!
dkubb
Brilliant, that's exactly what I needed. Thanks!
Tom