1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
5 # Protect referential integrity of owner_uuid columns in other tables
6 # that can refer to the uuid column in this table.
10 def self.included(base)
11 base.extend(ClassMethods)
13 # Rails' "has_many" can prevent us from destroying the owner
14 # record when other objects refer to it.
15 ActiveRecord::Base.connection.tables.each do |t|
16 next if t == base.table_name
19 'permission_refresh_lock',
20 'ar_internal_metadata',
34 klass = t.classify.constantize
35 next unless klass and 'owner_uuid'.in?(klass.columns.collect(&:name))
36 base.has_many(t.to_sym,
37 foreign_key: 'owner_uuid',
39 dependent: :restrict_with_exception)
41 # We need custom protection for changing an owner's primary
42 # key. (Apart from this restriction, admins are allowed to change
44 base.validate :restrict_uuid_change_breaking_associations
48 def install_view(type)
49 conn = ActiveRecord::Base.connection
51 # Check whether the temporary view has already been created
52 # during this connection. If not, create it.
53 conn.exec_query "SAVEPOINT check_#{type}_view"
55 conn.exec_query("SELECT 1 FROM #{type}_view LIMIT 0")
57 conn.exec_query "ROLLBACK TO SAVEPOINT check_#{type}_view"
58 sql = File.read(Rails.root.join("lib", "create_#{type}_view.sql"))
61 conn.exec_query "RELEASE SAVEPOINT check_#{type}_view"
67 def descendant_project_uuids
68 self.class.install_view('ancestor')
69 ActiveRecord::Base.connection.
70 exec_query('SELECT ancestor_view.uuid
72 LEFT JOIN groups ON groups.uuid=ancestor_view.uuid
73 WHERE ancestor_uuid = $1 AND groups.group_class = $2',
74 # "name" arg is a query label that appears in logs:
75 "descendant_project_uuids for #{self.uuid}",
76 # "binds" arg is an array of [col_id, value] for '$1' vars:
77 [self.uuid, 'project'],
78 ).rows.map do |project_uuid,|
85 def restrict_uuid_change_breaking_associations
86 return true if new_record? or not uuid_changed?
88 # Check for objects that have my old uuid listed as their owner.
89 self.class.reflect_on_all_associations(:has_many).each do |assoc|
90 next unless assoc.foreign_key == 'owner_uuid'
91 if assoc.klass.where(owner_uuid: uuid_was).any?
93 "cannot be changed on a #{self.class} that owns objects")
98 # if I owned myself before, I'll just continue to own myself with
100 if owner_uuid == uuid_was
101 self.owner_uuid = uuid