Last Updated: February 25, 2016
·
811
· timgluz

Workaround korma/fields variadic arguments

Korma is one of most popular Clojure SQL library.

As i started refactoring repeating parts of my data models into own namespace models.helpers, i encountered one weaknesses of its DSL - [korma.core/fields](https://github.com/korma/Korma/blob/v0.3.2/src/korma/core.clj#L202) uses variadic arguments for field's name, which makes it impossible to use it in high-level functions or compose with threading macros (->, ->>).

Therefore I wrote a little macro, which packs a list of fieldnames & aliases into korma.core/fields variadic arguments.


;; helper macro
(defmacro only-fields
    [query fields]
    `(let [field-list# (list* ~fields)
             fargs# (cons ~query field-list#)]
        (apply korma.core/fields fargs#)))

;; helper function
 (defn get-rows
    ;; this function returns all fields
    ([tbl-entity row-selectors]
      (korma/select tbl-entity
         (korma/where row-selectors)))

    ;; this one accepts field selector as 3rd argument
    ([tbl-entity row-selectors fields]
       (korma/select tbl-entity
         (only-fields fields)
         (korma/where row-selectors))))

;;usage
(defentity users)
(get-rows users [:firstname :lastname :gender [:lang :language]])
(get-rows users ["*"])

PS: i recommend to use Yesql as Clojure SQL library, because Korma seems to be retiring and SQL itself is already DSL, S-EXPR just adds extra noise.