Skip to content

Commit

Permalink
Enhance SQL query handling with joins in where clauses
Browse files Browse the repository at this point in the history
Improved the handling of join conditions within where clauses by ensuring all involved tables are included in the filter builder context. Added a test to validate the combination of join and where clauses in SQL query creation. This change enhances the query-building capabilities, allowing for more complex and accurate SQL queries.
  • Loading branch information
eliasjpr committed Aug 14, 2024
1 parent 30fe804 commit 40d8dda
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
20 changes: 20 additions & 0 deletions spec/query_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,26 @@ describe Cql::Query do
select_query.should eq({output, ["John", 1]})
end

it "combines join with where clause" do
select_query = Northwind.query.from(:users)
.select(users: [:name, :email], address: [:street, :city])
.inner(:address) do
users.id.eq(address.user_id)
end
.where do
users.name.eq("John") | users.id.eq(1)
end.to_sql

output = <<-SQL.gsub(/\n/, " ").strip
SELECT users.name, users.email, address.street, address.city
FROM users
INNER JOIN address ON users.id = address.user_id
WHERE (users.name = ? OR users.id = ?)
SQL

select_query.should eq({output, ["John", 1]})
end

it "Creates indexes for table" do
index = Cql::Index.new(Northwind.tables[:users], [:name, :email], unique: true)

Expand Down
10 changes: 8 additions & 2 deletions src/query.cr
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,13 @@ module Cql
# => "SELECT * FROM users WHERE name = 'John'"
# ```
def where(&)
builder = with Expression::FilterBuilder.new(@tables) yield
all_tables = @tables.dup

@joins.each do |j|
all_tables[j.table.table.table_name] = j.table.table
end

builder = with Expression::FilterBuilder.new(all_tables) yield
@where = Expression::Where.new(builder.as(Expression::ConditionBuilder).condition)
self
end
Expand Down Expand Up @@ -397,7 +403,7 @@ module Cql
join_table = Expression::Table.new(tbl)
tables = @tables.dup
tables[table] = tbl
builder = with Expression::FilterBuilder.new(tables) yield
builder = with Expression::FilterBuilder.new(tables) yield table_expr
@joins << Expression::Join.new(Expression::JoinType::INNER, join_table, builder.condition)
self
end
Expand Down

0 comments on commit 40d8dda

Please sign in to comment.