The Silver Lining

Lessons & Learnings from a salesforce certified technical architect.

“Dropping” a mongohq database on Heroku

leave a comment »

I’ve used inverted commas around the word ‘dropping’ because it doesn’t look like you can drop a mongohq database – what you can do however is drop all the collections in the database. I was doing this through the add-on interface in heroku but that got tired quickly, and after some googling it looked like the solution was to write a custom rake task and drop it into lib/tasks/; the file can be named anything with a ‘.rb’ extension. The code follows:

namespace :mdb do
    desc 'Drops all the collections for the database for the current Rails.env'
    task :drop => :environment do
      if ENV['MONGOHQ_URL']
        uri = URI.parse(ENV['MONGOHQ_URL'])
        conn = Mongo::Connection.from_uri(ENV['MONGOHQ_URL'])
        DB = conn.db(uri.path.gsub(/^\//, ''))
        DB.collections.each do |collection|
          begin
            collection.drop
          rescue
            puts "Can't drop: " + collection.name
          end
        end

      end
    end
end

Note that the exception handler isn’t perfect and essentially all I’m doing is skipping the system collections that can’t be dropped.
Once you’ve deployed this code to the heroku servers it’s simple to execute:

heroku rake mdb:drop
Advertisements

Written by Wes

October 2, 2011 at 5:05 pm

Posted in Ruby

Tagged with , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: