4823: Add new tests for BufferBlock, BlockManager, saving, updating. Stylistic
[arvados.git] / services / api / db / migrate / 20140817035914_add_unique_name_constraints.rb
1 class AddUniqueNameConstraints < ActiveRecord::Migration
2   def change
3     # Ensure uniqueness before adding constraints.
4     ["collections", "pipeline_templates", "groups"].each do |table|
5       rows = ActiveRecord::Base.connection.select_all %{
6 select uuid, owner_uuid, name from #{table} order by owner_uuid, name
7 }
8       prev = {}
9       n = 1
10       rows.each do |r|
11         if r["owner_uuid"] == prev["owner_uuid"] and !r["name"].nil? and r["name"] == prev["name"]
12           n += 1
13           ActiveRecord::Base.connection.execute %{
14 update #{table} set name='#{r["name"]} #{n}' where uuid='#{r["uuid"]}'
15 }
16         else
17           n = 1
18         end
19         prev = r
20       end
21     end
22
23     add_index(:collections, [:owner_uuid, :name], unique: true,
24               name: 'collection_owner_uuid_name_unique')
25     add_index(:pipeline_templates, [:owner_uuid, :name], unique: true,
26               name: 'pipeline_template_owner_uuid_name_unique')
27     add_index(:groups, [:owner_uuid, :name], unique: true,
28               name: 'groups_owner_uuid_name_unique')
29   end
30 end