Add fix for select distinct on

This commit is contained in:
Unnikrishnan 2016-04-04 18:34:18 +05:30
parent 43df955a86
commit 21b4cea2c2
2 changed files with 18 additions and 1 deletions

View file

@ -17,6 +17,14 @@
(defn paren-wrap [x] (defn paren-wrap [x]
(str "(" x ")")) (str "(" x ")"))
;; Checks if the first is a `DISTINCT ON` statement, if yes then return a string
;; with an appended space at the end of the first and then comma joining the rest
;; else simply return a comma joined string
(defn construct-select [s]
(if (re-find #"DISTINCT ON" (first s))
(str (first s) " " (comma-join (rest s)))
(comma-join s)))
(def ^:dynamic *clause* (def ^:dynamic *clause*
"During formatting, *clause* is bound to :select, :from, :where, etc." "During formatting, *clause* is bound to :select, :from, :where, etc."
nil) nil)
@ -405,7 +413,7 @@
(str (space-join (map (comp string/upper-case name) (str (space-join (map (comp string/upper-case name)
(:modifiers sql-map))) (:modifiers sql-map)))
" ")) " "))
(comma-join (map to-sql fields)))) (construct-select (map to-sql fields))))
(defmethod format-clause :from [[_ tables] _] (defmethod format-clause :from [[_ tables] _]
(str "FROM " (comma-join (map to-sql tables)))) (str "FROM " (comma-join (map to-sql tables))))

View file

@ -173,3 +173,12 @@
(from :foo) (from :foo)
(join :x [:= :foo.id :x.id] :y nil) (join :x [:= :foo.id :x.id] :y nil)
sql/format))))) sql/format)))))
(deftest distinct-on
(testing "Distinct on"
(is (= ["SELECT DISTINCT ON (name) name, created_by"]
(-> (select (sql/call :distinct-on :name) :name :created_by)
sql/format)))
(is (= ["SELECT DISTINCT ON (name, created_by) name, created_by"]
(-> (select (sql/call :distinct-on :name :created_by) :name :created_by)
sql/format)))))