Skip to content

Commit 6de0c26

Browse files
Ian Bishopkriyative
Ian Bishop
authored andcommitted
Add support for where in, select distinct (#9)
* Using - throws uncaught exception * Add support for select distinct and where in
1 parent fc38fba commit 6de0c26

File tree

2 files changed

+35
-3
lines changed

2 files changed

+35
-3
lines changed

src/sqly/core.clj

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@
44
[camel-snake-kebab.core :refer [->snake_case]]))
55

66
(def ^:dynamic *output-ident-style*
7-
#(->snake_case %1 :separator "-"))
7+
#(try
8+
(->snake_case %1 :separator "-")
9+
(catch Exception _
10+
%1)))
811

912
(defmacro with-output-ident-style [f & body]
1013
`(binding [*output-ident-style* ~f]
@@ -98,6 +101,12 @@
98101
"and"
99102
(as-ident higher opts)])))
100103

104+
(defn emit-in
105+
([v]
106+
(emit-in v {}))
107+
([v opts]
108+
(emit-infix-op v (assoc opts :separator ","))))
109+
101110
(defn emit-literal-identifier
102111
([v]
103112
(emit-literal-identifier v {}))
@@ -126,6 +135,7 @@
126135
(def-ops #'emit-sql '[sql])
127136
(def-ops #'emit-between '[between])
128137
(def-ops #'emit-literal-identifier '[ident])
138+
(def-ops #'emit-in '[in])
129139

130140
(defn emit-function
131141
([v]
@@ -234,7 +244,9 @@
234244
(fn [[k v]]
235245
(if ((set (keys *remapped-idents*)) v)
236246
[k v]
237-
(list '= k v)))))
247+
(if (coll? v)
248+
(list 'in k v)
249+
(list '= k v))))))
238250
expr (if (< (count expr) 1)
239251
(list* 'and expr)
240252
(cons 'and expr))]
@@ -262,14 +274,15 @@
262274
(str/join " "))))
263275

264276
(defn emit-select [{:keys [select
277+
distinct?
265278
from
266279
where
267280
order-by
268281
group-by
269282
limit
270283
join]}]
271284
(when select
272-
(->> [["select" select]
285+
(->> [[(str "select" (when distinct? " distinct")) select]
273286
["from" from #'emit-from-clause]
274287
["where" where #'emit-where-clause]
275288
["group by" group-by]

test/sqly/core_test.clj

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -371,3 +371,22 @@
371371
{:select [:related_id :type :description]
372372
:from :b_events
373373
:where {:related_id "{{related-id}}"}}]}))))
374+
375+
(deftest select-distinct-test
376+
(is (= (canon
377+
["select distinct id1,id2,id3 from a_events"])
378+
(sql/sql
379+
'{:select [:id1 :id2 :id3]
380+
:distinct? true
381+
:from :a_events}))))
382+
383+
(deftest where-in-test
384+
(is (= (canon
385+
["select id,name from a_events"
386+
" where (id in ('foo','bar'))"
387+
" and (name = 'baz')"])
388+
(sql/sql
389+
'{:select [:id :name]
390+
:from :a_events
391+
:where {:id ["foo" "bar"]
392+
:name "baz"}}))))

0 commit comments

Comments
 (0)