Skip to content

Commit

Permalink
Extract PrimaryKeyQueryable from Queryable
Browse files Browse the repository at this point in the history
  • Loading branch information
Matthew McGarvey committed Sep 7, 2020
1 parent fedd1be commit 0acd88a
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 16 deletions.
2 changes: 1 addition & 1 deletion src/avram/base_query_template.cr
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ class Avram::BaseQueryTemplate
private class Nothing
end

include Avram::Queryable({{ type }})
include Avram::PrimaryKeyQueryable({{ type }})

def database : Avram::Database.class
{{ type }}.database
Expand Down
27 changes: 27 additions & 0 deletions src/avram/primary_key_queryable.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
require "./errors"
require "./queryable"

module Avram::PrimaryKeyQueryable(T)
abstract def id
abstract def id(id_val)

macro included
include Avram::Queryable(T)

def self.find(id)
new.find(id)
end

def find(id)
id(id).limit(1).first? || raise Avram::RecordNotFoundError.new(model: @@table_name, id: id.to_s)
end

private def ordered_query
if query.ordered?
query
else
id.asc_order.query
end
end
end
end
16 changes: 1 addition & 15 deletions src/avram/queryable.cr
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
module Avram::Queryable(T)
include Enumerable(T)

abstract def id

@query : Avram::QueryBuilder?
setter query

Expand All @@ -17,10 +15,6 @@ module Avram::Queryable(T)
new
end

def self.find(id)
new.find(id)
end

def self.first
new.first
end
Expand Down Expand Up @@ -155,10 +149,6 @@ module Avram::Queryable(T)
self
end

def find(id)
id(id).limit(1).first? || raise RecordNotFoundError.new(model: @@table_name, id: id.to_s)
end

def first?
ordered_query.limit(1)
results.first?
Expand Down Expand Up @@ -213,11 +203,7 @@ module Avram::Queryable(T)
end

private def ordered_query
if query.ordered?
query
else
id.asc_order.query
end
query
end

def to_sql
Expand Down

0 comments on commit 0acd88a

Please # to comment.