Skip to content

Commit

Permalink
Fixing clone for distincts (#285)
Browse files Browse the repository at this point in the history
* updating how query builder distinct is handled to allow cloning the distinct from queries. Fixes #284

* Removed some unnecessary code from a spec.

* moved the raw_distinct method over to a gitter to clean up a bit
  • Loading branch information
jwoertink authored Jan 3, 2020
1 parent 85b6b3d commit d1d6b63
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
7 changes: 7 additions & 0 deletions spec/query_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -705,6 +705,13 @@ describe Avram::Query do
cloned_products.first.line_items.first.price.should_not be_nil
end
end

it "clones distinct queries" do
original_query = Post::BaseQuery.new.distinct_on(&.title).clone
new_query = original_query.published_at.is_nil

new_query.to_sql[0].should contain "DISTINCT ON"
end
end

describe "#between" do
Expand Down
14 changes: 10 additions & 4 deletions src/avram/query_builder.cr
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
class Avram::QueryBuilder
alias ColumnName = Symbol | String
getter table
getter distinct_on : String | Symbol | Nil = nil
@limit : Int32?
@offset : Int32?
@wheres = [] of Avram::Where::SqlClause
Expand All @@ -12,7 +13,6 @@ class Avram::QueryBuilder
@prepared_statement_placeholder = 0
@distinct : Bool = false
@delete : Bool = false
@distinct_on : String | Symbol | Nil = nil

def initialize(@table : Symbol)
end
Expand Down Expand Up @@ -61,6 +61,8 @@ class Avram::QueryBuilder
def clone(query_to_merge : Avram::QueryBuilder)
merge(query_to_merge)
self.select(query_to_merge.selects)
distinct if query_to_merge.distinct?
distinct_on(query_to_merge.distinct_on.to_s) if query_to_merge.has_distinct_on?
limit(query_to_merge.limit)
offset(query_to_merge.offset)
end
Expand Down Expand Up @@ -125,8 +127,12 @@ class Avram::QueryBuilder
self
end

private def distinct?
@distinct || @distinct_on
def distinct?
@distinct || has_distinct_on?
end

def has_distinct_on?
!!@distinct_on
end

def limit
Expand Down Expand Up @@ -252,7 +258,7 @@ class Avram::QueryBuilder
String.build do |sql|
sql << "SELECT "
sql << "DISTINCT " if distinct?
sql << "ON (#{@distinct_on}) " if @distinct_on
sql << "ON (#{@distinct_on}) " if has_distinct_on?
sql << @selections
sql << " FROM "
sql << table
Expand Down

0 comments on commit d1d6b63

Please sign in to comment.