21700: Install Bundler system-wide in Rails postinst
[arvados.git] / services / api / db / migrate / 20221219165512_dedup_permission_links.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require 'update_permissions'
6
7 class DedupPermissionLinks < ActiveRecord::Migration[5.2]
8   include CurrentApiClient
9   def up
10     act_as_system_user do
11       batch_update_permissions do
12         rows = ActiveRecord::Base.connection.select_all("SELECT MIN(uuid) AS uuid, COUNT(uuid) AS n FROM links
13           WHERE tail_uuid IS NOT NULL
14            AND head_uuid IS NOT NULL
15            AND link_class = 'permission'
16            AND name in ('can_read', 'can_write', 'can_manage')
17           GROUP BY (tail_uuid, head_uuid)
18           HAVING COUNT(uuid) > 1")
19         rows.each do |row|
20           Rails.logger.debug "DedupPermissionLinks: consolidating #{row['n']} links into #{row['uuid']}"
21           link = Link.find_by_uuid(row['uuid'])
22           # This no-op update has the side effect that the update hooks
23           # will merge the highest available permission into this one
24           # and then delete the others.
25           link.update!(properties: link.properties.dup)
26         end
27
28         rows = ActiveRecord::Base.connection.select_all("SELECT MIN(uuid) AS uuid, COUNT(uuid) AS n FROM links
29           WHERE tail_uuid IS NOT NULL
30            AND head_uuid IS NOT NULL
31            AND link_class = 'permission'
32            AND name = 'can_login'
33           GROUP BY (tail_uuid, head_uuid, properties)
34           HAVING COUNT(uuid) > 1")
35         rows.each do |row|
36           Rails.logger.debug "DedupPermissionLinks: consolidating #{row['n']} links into #{row['uuid']}"
37           link = Link.find_by_uuid(row['uuid'])
38           link.update!(properties: link.properties.dup)
39         end
40       end
41     end
42   end
43   def down
44     # no-op -- restoring redundant records would still be redundant
45   end
46 end