Skip to content

Commit

Permalink
fix scopes utilizing potentionally nil denormalized foreign key
Browse files Browse the repository at this point in the history
  • Loading branch information
ezekg committed Apr 2, 2024
1 parent 071d820 commit 6f148f6
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 22 deletions.
9 changes: 8 additions & 1 deletion app/models/machine.rb
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,14 @@ class ResurrectionExpiredError < StandardError; end
)
end
}
scope :for_product, -> id { joins(:license).where license: { product_id: id } }

# FIXME(ezekg) Remove this once we can assert product_id is fully denormalized.
if License.exists?(product_id: nil)
scope :for_product, -> id { joins(:product).where(product: { id: }) }
else
scope :for_product, -> id { joins(:license).where(license: { product_id: id }) }
end

scope :for_policy, -> id { joins(:license).where license: { policy_id: id } }
scope :for_group, -> id { where(group: id) }

Expand Down
28 changes: 7 additions & 21 deletions app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -290,27 +290,13 @@ def owned = where(owner: proxy_association.owner)
end
}

scope :for_product, -> id {
license_users = LicenseUser.arel_table
licenses = License.arel_table
users = User.arel_table

# More optimized union query for this particular association
left_outer_joins(:license_users)
.joins(
Arel::Nodes::InnerJoin.new(
licenses,
Arel::Nodes::On.new(
licenses[:user_id].eq(users[:id]).or(
licenses[:id].eq(license_users[:license_id]),
)
),
),
)
.where(
licenses: { product_id: id },
)
}
# FIXME(ezekg) Remove this once we can assert product_id is fully denormalized.
if License.exists?(product_id: nil)
scope :for_product, -> id { joins(:products).where(products: { id: }).distinct }
else
scope :for_product, -> id { joins(:licenses).where(licenses: { product_id: id }).distinct }
end

scope :for_license, -> id { joins(:licenses).where(licenses: { id: id }).distinct }
scope :for_group_owner, -> id { joins(group: :owners).where(group: { group_owners: { user_id: id } }).distinct }
scope :for_user, -> id {
Expand Down

0 comments on commit 6f148f6

Please sign in to comment.