53 lines
1.3 KiB
Org Mode
53 lines
1.3 KiB
Org Mode
#+TITLE: HoneySQL tips & tricks
|
|
|
|
* Basic statements
|
|
|
|
#+BEGIN_SRC clojurescript :tangle ./src/core.cljs
|
|
#_(ns core.demo
|
|
(:require
|
|
[honey.sql :as sql]
|
|
[honey.sql.helpers :as sqlh]))
|
|
#+END_SRC
|
|
|
|
#+BEGIN_SRC clojurescript :tangle ./src/core.cljs
|
|
(clojure.core/into [:a] [1 2 3 4])
|
|
#+END_SRC
|
|
|
|
** Simple table select, with filtering and sorting applied
|
|
#+BEGIN_SRC clojurescript
|
|
(-> (sqlh/select :*)
|
|
(sqlh/from :company)
|
|
(sqlh/where [:= :id 1]))
|
|
#+END_SRC
|
|
|
|
#+BEGIN_SRC clojurescript :tangle ./src/core.cljs
|
|
(sqlh/select :*)
|
|
#+END_SRC
|
|
|
|
|
|
** Dynamic where clauses
|
|
|
|
*** where value exists
|
|
=sqlh/where= will only be applied to the query if it has a value so nil on its own will not applied
|
|
#+BEGIN_SRC clojurescript :tangle ./src/core.cljs
|
|
(defn conditional-where [id]
|
|
(-> (sqlh/select :*)
|
|
(sqlh/from [:company])
|
|
(sqlh/where (when id [:= :id id]))))
|
|
|
|
(first (sql/format (conditional-where 1) {:pretty true}))
|
|
#+END_SRC
|
|
|
|
*** Switch between singular or multiple values in condition
|
|
|
|
#+BEGIN_SRC clojurescript :tangle ./src/core.cljs
|
|
(defn conditional-where [id]
|
|
(-> (sqlh/select :*)
|
|
(sqlh/from [:company])
|
|
(sqlh/where (if (sequential? id) [:in :id id] [:= :id id]))))
|
|
|
|
(first (sql/format (conditional-where [1 2 3]) {:pretty true}))
|
|
;(clojure.string/join "" (sql/format (conditional-where [1 2 3]) {:pretty true}))
|
|
#+END_SRC
|
|
|