Skip to content

Commit

Permalink
feat (Query): add select(nil) method
Browse files Browse the repository at this point in the history
Closes #78
  • Loading branch information
vladfaust committed Mar 9, 2019
1 parent b0cd32d commit 473d741
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
10 changes: 10 additions & 0 deletions spec/query/select_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,14 @@ describe "Query#select" do
params.should be_empty
end
end

context "with nil call" do
it do
q = Query(User).new.select(nil)

expect_raises Exception do
q.build
end
end
end
end
24 changes: 24 additions & 0 deletions src/onyx-sql/query/select.cr
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,28 @@ module Onyx::SQL
self
end

# Reset current query selects. This will lead to empty select clause for this partucular
# query. It's useful when on joining. However, it would raise in runtime if the resulting
# query has no actual selects.
#
# ```
# Post.select(nil).build # "Cannot build a query with empty SELECT clause" runtime error
#
# q = Post.select(nil).join(author: true) { |x| x.select(:username) }
# q.build # => {"SELECT author.username FROM posts JOIN user AS author ..."}
# ```
#
# NOTE: If you call it *after* join, then it will erase everything:
#
# ```crystal
# Post.join(author: true) { |x| x.select(:username) }.select(nil).build
# # Cannot build a query with empty SELECT clause
# ```
def select(nil_value : Nil)
@select = Deque(String).new
self
end

@select : Deque(String)? = nil

protected def get_select
Expand All @@ -123,6 +145,8 @@ module Onyx::SQL

protected def append_select(sql, *args)
if selects = @select
raise "Cannot build a query with empty SELECT clause" if selects.empty?

sql << "SELECT "

first = true
Expand Down

0 comments on commit 473d741

Please sign in to comment.