From d20c9d1a1709ff3eca9b6b4df42ee023ae34a994 Mon Sep 17 00:00:00 2001 From: Andrew Buntine Date: Tue, 10 Sep 2024 02:31:52 +1000 Subject: [PATCH] feat: Add support for table alias when injecting ONLY clause (#45) * feat: Add support for table alias when injecting ONLY clause * chore: Bumped version to 0.15.1 * fix: Linting --- lib/hoardable/arel_visitors.rb | 12 +++++++++--- lib/hoardable/version.rb | 2 +- test/support/models.rb | 2 ++ test/test_model.rb | 7 +++++++ 4 files changed, 19 insertions(+), 4 deletions(-) diff --git a/lib/hoardable/arel_visitors.rb b/lib/hoardable/arel_visitors.rb index c84ad04..c50ceaf 100644 --- a/lib/hoardable/arel_visitors.rb +++ b/lib/hoardable/arel_visitors.rb @@ -40,10 +40,16 @@ def visit_Arel_Nodes_InnerJoin(o, collector) end private def hoardable_maybe_add_only(o, collector) - return unless o.left.instance_variable_get("@klass").in?(Hoardable::REGISTRY) - return if Hoardable.instance_variable_get("@at") + left = o.left - collector << "ONLY " + if left.is_a?(Arel::Nodes::TableAlias) + hoardable_maybe_add_only(left, collector) + else + return unless left.instance_variable_get("@klass").in?(Hoardable::REGISTRY) + return if Hoardable.instance_variable_get("@at") + + collector << "ONLY " + end end end end diff --git a/lib/hoardable/version.rb b/lib/hoardable/version.rb index cb0d3ea..4e7b158 100644 --- a/lib/hoardable/version.rb +++ b/lib/hoardable/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Hoardable - VERSION = "0.15.0" + VERSION = "0.15.1" end diff --git a/test/support/models.rb b/test/support/models.rb index 66b86ad..1e6f601 100644 --- a/test/support/models.rb +++ b/test/support/models.rb @@ -84,6 +84,8 @@ class Like < ActiveRecord::Base class UserWithTrashedPosts < ActiveRecord::Base self.table_name = "users" has_many :posts, -> { include_versions }, foreign_key: "user_id" + + has_one :bio, class_name: "Profile", foreign_key: "user_id" end class Current < ActiveSupport::CurrentAttributes diff --git a/test/test_model.rb b/test/test_model.rb index 2b51d02..2f6026b 100644 --- a/test/test_model.rb +++ b/test/test_model.rb @@ -663,4 +663,11 @@ def create_comments_and_destroy_post assert_empty user.posts assert_empty User.joins(:posts) end + + test "applys ONLY clause on joined relationship with aliased name" do + assert_equal( + "SELECT \"users\".* FROM \"users\" INNER JOIN ONLY \"profiles\" \"bio\" ON \"bio\".\"user_id\" = \"users\".\"id\" WHERE \"bio\".\"id\" = 999", + UserWithTrashedPosts.joins(:bio).where(bio: { id: 999 }).to_sql + ) + end end