Skip to content

Commit

Permalink
feat: Add support for table alias when injecting ONLY clause (#45)
Browse files Browse the repository at this point in the history
* feat: Add support for table alias when injecting ONLY clause

* chore: Bumped version to 0.15.1

* fix: Linting
  • Loading branch information
buntine authored Sep 9, 2024
1 parent 279ebb1 commit d20c9d1
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 4 deletions.
12 changes: 9 additions & 3 deletions lib/hoardable/arel_visitors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion lib/hoardable/version.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# frozen_string_literal: true

module Hoardable
VERSION = "0.15.0"
VERSION = "0.15.1"
end
2 changes: 2 additions & 0 deletions test/support/models.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions test/test_model.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit d20c9d1

Please sign in to comment.