Skip to content

Commit

Permalink
Fixes Issue #91: SystemStackError when using .with (#105)
Browse files Browse the repository at this point in the history
Signed-off-by: Garrett Blehm <[email protected]>
  • Loading branch information
garrettblehm authored Jul 22, 2024
1 parent af20771 commit 2e2cfd9
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/active_record_extended/query_methods/with_cte.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ def pipe_cte_with!(value)
# Ensure we follow FIFO pattern.
# If the parent has similar CTE alias keys, we want to favor the parent's expressions over its children's.
if expression.is_a?(ActiveRecord::Relation) && expression.with_values?
expression.cte = expression.cte.dup if expression.cte

# Add child's materialized keys to the parent
@materialized_keys += expression.cte.materialized_keys
@not_materialized_keys += expression.cte.not_materialized_keys
Expand Down
15 changes: 15 additions & 0 deletions spec/query_methods/with_cte_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,5 +67,20 @@
expect(query).to contain_exactly(user_two)
end
end

context "when the relation uses itself as a second CTE" do
it "works without a SystemStackError" do
user_relation = User.all

# Add first CTE to User Relation
group_relation = Group.all
user_relation_with_cte = user_relation.with('first_cte' => group_relation)

# User Relation with a CTE adds itself as another CTE
user_relation_with_self_cte = user_relation_with_cte.with('self_cte' => user_relation_with_cte)

expect(user_relation_with_self_cte).to contain_exactly(user_one,user_two)
end
end
end
end

0 comments on commit 2e2cfd9

Please sign in to comment.