Skip to content

Commit

Permalink
Let the table_name of a query object be overriden.
Browse files Browse the repository at this point in the history
  • Loading branch information
jwoertink committed Mar 18, 2024
1 parent 3b2b4d9 commit cb08245
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 6 deletions.
13 changes: 8 additions & 5 deletions spec/avram/query_associations_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -177,15 +177,18 @@ describe "Query associations" do
result.should eq(product)
end

it "handles aliases", focus: true do
it "handles aliases" do
interviewer = UserFactory.create(&.available_for_hire(false).name("Interviewer"))
interviewee = UserFactory.create(&.available_for_hire(true).name("Interviewee"))
UserFactory.create(&.available_for_hire(false).name("Employed"))
employed = UserFactory.create(&.available_for_hire(false).name("Employed"))
InterviewFactory.create(&.interviewee(interviewee).interviewer(interviewer))
InterviewFactory.create(&.interviewee(employed).interviewer(interviewer))

InterviewQuery.new
.where_interviewer(UserQuery.new.available_for_hire(false))
.where_interviewee(UserQuery.new.available_for_hire(true))
.to_prepared_sql.should eq("nothing")
.join(Avram::Join::Inner.new(:interviews, :users, alias_to: :interviewers, primary_key: :interviewer_id, foreign_key: :id))
.join(Avram::Join::Inner.new(:interviews, :users, alias_to: :interviewees, primary_key: :interviewee_id, foreign_key: :id))
.where_interviewer(UserQuery.new("interviewers").available_for_hire(false), auto_inner_join: false)
.where_interviewee(UserQuery.new("interviewees").available_for_hire(true), auto_inner_join: false)
.select_count.should eq(1)
end
end
5 changes: 5 additions & 0 deletions src/avram/base_query_template.cr
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ class Avram::BaseQueryTemplate
def_clone
include Avram::Queryable({{ type }})

getter table_name : String = {{ type }}.table_name

def initialize(@table_name : String = {{ type }}.table_name)
end

{% if type.resolve.has_constant?("PRIMARY_KEY_NAME") %}
include Avram::PrimaryKeyQueryable({{ type }})
{% end %}
Expand Down
2 changes: 1 addition & 1 deletion src/avram/queryable.cr
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ module Avram::Queryable(T)
.select(schema_class.column_names)
end

delegate :database, :table_name, :primary_key_name, to: T
delegate :database, :primary_key_name, to: T

macro included
def self.new_with_existing_query(query : Avram::QueryBuilder)
Expand Down

0 comments on commit cb08245

Please sign in to comment.