Skip to content

Commit 3b2b4d9

Browse files
committedMar 17, 2024
Merge branch 'main' into issues/1011
2 parents 97758ab + 9f727d2 commit 3b2b4d9

File tree

2 files changed

+24
-7
lines changed

2 files changed

+24
-7
lines changed
 

‎spec/avram/join_spec.cr

+6
Original file line numberDiff line numberDiff line change
@@ -36,4 +36,10 @@ describe Avram::Join do
3636
.to_sql
3737
.should eq "INNER JOIN managers USING (company_id, department_id)"
3838
end
39+
40+
it "allows aliasing the to table" do
41+
Avram::Join::Inner.new(from: :purchases, to: :users, alias_to: :sellers, primary_key: :seller_id, foreign_key: :id)
42+
.to_sql
43+
.should eq "INNER JOIN users AS sellers ON purchases.seller_id = sellers.id"
44+
end
3945
end

‎src/avram/join.cr

+18-7
Original file line numberDiff line numberDiff line change
@@ -3,34 +3,45 @@ require "wordsmith"
33
module Avram::Join
44
abstract class SqlClause
55
getter from : TableName
6-
getter to : TableName
76

87
def initialize(
98
@from : TableName,
109
@to : TableName,
1110
@primary_key : Symbol? = nil,
1211
@foreign_key : Symbol? = nil,
1312
@comparison : String? = "=",
14-
@using : Array(Symbol) = [] of Symbol
13+
@using : Array(Symbol) = [] of Symbol,
14+
@alias_to : TableName? = nil
1515
)
1616
end
1717

1818
abstract def join_type : String
1919

2020
def to_sql : String
21-
if !@using.empty?
22-
%(#{join_type} JOIN #{@to} USING (#{@using.join(", ")}))
23-
else
24-
"#{join_type} JOIN #{@to} ON #{from_column} #{@comparison} #{to_column}"
21+
String.build do |io|
22+
io << "#{join_type} JOIN "
23+
@to.to_s(io)
24+
if @alias_to
25+
io << " AS #{@alias_to}"
26+
end
27+
if !@using.empty?
28+
io << " USING (#{@using.join(", ")})"
29+
else
30+
io << " ON #{from_column} #{@comparison} #{to_column}"
31+
end
2532
end
2633
end
2734

35+
def to : TableName
36+
@alias_to || @to
37+
end
38+
2839
def from_column : String
2940
"#{@from}.#{@primary_key || "id"}"
3041
end
3142

3243
def to_column : String
33-
"#{@to}.#{@foreign_key || default_foreign_key}"
44+
"#{to}.#{@foreign_key || default_foreign_key}"
3445
end
3546

3647
def default_foreign_key : String

0 commit comments

Comments
 (0)
Please sign in to comment.