diff --git a/spec/avram/join_spec.cr b/spec/avram/join_spec.cr index cacb0e51f..06d60f6a8 100644 --- a/spec/avram/join_spec.cr +++ b/spec/avram/join_spec.cr @@ -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 diff --git a/src/avram/join.cr b/src/avram/join.cr index e09136913..a3b566bc0 100644 --- a/src/avram/join.cr +++ b/src/avram/join.cr @@ -3,7 +3,6 @@ require "wordsmith" module Avram::Join abstract class SqlClause getter from : TableName - getter to : TableName def initialize( @from : TableName, @@ -11,26 +10,38 @@ module Avram::Join @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