Skip to content
bgapinski edited this page Feb 27, 2012 · 2 revisions

This is the code to generate UUIDs for all of the CouchDB documents. To run it, just switch the two instances of roomtrol-dev1 with the desired box. It will create a new database in couch with UUIDs. Just delete the old rooms database (after backing it up) and create a new rooms database with the new documents. require 'couchrest' require 'uuidtools'

@db = CouchRest.database("http://roomtrol-dev1.class:5984/rooms")
@id_map = {}
@clone = CouchRest.database("http://roomtrol-dev1.class:5984/new-rooms")
@clone.create!
@docs = []

@db.all_docs["rows"].each do |row|
  @docs << @db.get(row["id"]).to_hash
end

@docs.each do |doc|
  old_id = doc["_id"]
  if !old_id.start_with?("_design")
    new_id = UUIDTools::UUID.random_create.to_s

    # This part makes sure that the action documents
    # stay in order so that they are displayed in the
    # proper order.
    if doc.has_key?("action") && doc["action"]
      while @actions[-1] && new_id < @actions[-1]
        new_id = UUIDTools::UUID.random_create.to_s
      end
      @actions << new_id
    end

    doc["_id"] = new_id
    @id_map[old_id] = new_id
  end
end

@docs.each do |doc|
  if doc.has_key?("belongs_to")
    doc["belongs_to"] = @id_map[doc["belongs_to"]]
  end
  if doc.has_key?("settings")
    old = doc["settings"]["source"]
    doc["settings"]["source"] = @id_map[old]
  end
  doc.delete "_rev"
  @clone.save_doc(doc)
end