clojure-demos/reagent-reitit-demo/resources/public/documents/honey-sql-demo.org

1.3 KiB

HoneySQL tips & tricks

Basic statements

#_(ns core.demo
  (:require
   [honey.sql :as sql]
   [honey.sql.helpers :as sqlh]))
(clojure.core/into [:a] [1 2 3 4])

Simple table select, with filtering and sorting applied

(-> (sqlh/select :*)
    (sqlh/from :company)
    (sqlh/where [:= :id 1]))
(sqlh/select :*)

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

(defn conditional-where [id] 
  (-> (sqlh/select :*)
      (sqlh/from [:company])
      (sqlh/where (when id [:= :id id]))))

(first (sql/format (conditional-where 1) {:pretty true}))

Switch between singular or multiple values in condition

(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}))