Skip to content

Commit

Permalink
Merge branch 'main' into issues/1011
Browse files Browse the repository at this point in the history
  • Loading branch information
jwoertink committed Mar 17, 2024
2 parents 97758ab + 9f727d2 commit 3b2b4d9
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
6 changes: 6 additions & 0 deletions spec/avram/join_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,10 @@ describe Avram::Join do
.to_sql
.should eq "INNER JOIN managers USING (company_id, department_id)"
end

it "allows aliasing the to table" do
Avram::Join::Inner.new(from: :purchases, to: :users, alias_to: :sellers, primary_key: :seller_id, foreign_key: :id)
.to_sql
.should eq "INNER JOIN users AS sellers ON purchases.seller_id = sellers.id"
end
end
25 changes: 18 additions & 7 deletions src/avram/join.cr
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,45 @@ require "wordsmith"
module Avram::Join
abstract class SqlClause
getter from : TableName
getter to : TableName

def initialize(
@from : TableName,
@to : TableName,
@primary_key : Symbol? = nil,
@foreign_key : Symbol? = nil,
@comparison : String? = "=",
@using : Array(Symbol) = [] of Symbol
@using : Array(Symbol) = [] of Symbol,
@alias_to : TableName? = nil
)
end

abstract def join_type : String

def to_sql : String
if !@using.empty?
%(#{join_type} JOIN #{@to} USING (#{@using.join(", ")}))
else
"#{join_type} JOIN #{@to} ON #{from_column} #{@comparison} #{to_column}"
String.build do |io|
io << "#{join_type} JOIN "
@to.to_s(io)
if @alias_to
io << " AS #{@alias_to}"
end
if !@using.empty?
io << " USING (#{@using.join(", ")})"
else
io << " ON #{from_column} #{@comparison} #{to_column}"
end
end
end

def to : TableName
@alias_to || @to
end

def from_column : String
"#{@from}.#{@primary_key || "id"}"
end

def to_column : String
"#{@to}.#{@foreign_key || default_foreign_key}"
"#{to}.#{@foreign_key || default_foreign_key}"
end

def default_foreign_key : String
Expand Down

0 comments on commit 3b2b4d9

Please sign in to comment.