Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Extract PrimaryKeyQueryable from Queryable #455

Merged
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/avram/base_query_template.cr
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ class Avram::BaseQueryTemplate

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

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

module Avram::PrimaryKeyQueryable(T)
macro included
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 with_ordered_query : self
if query.ordered?
self
else
id.asc_order
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 @@ -149,10 +143,6 @@ module Avram::Queryable(T)
clone.tap &.query.offset(amount)
end

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

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

private def with_ordered_query : self
if query.ordered?
self
else
id.asc_order
end
self
end

def to_sql
Expand Down