Skip to content

Instantly share code, notes, and snippets.

@mishok13
Last active August 29, 2015 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mishok13/8687718 to your computer and use it in GitHub Desktop.
Save mishok13/8687718 to your computer and use it in GitHub Desktop.
user> (require '[korma.core :as sql])
nil
user> (def q (-> (sql/select* :test)
(sql/fields :foo :bar)))
#'user/q
;; Just looking whether the query is correct
user> (sql/as-sql q)
"SELECT \"test\".\"foo\", \"test\".\"bar\" FROM \"test\""
;; Introducing a simple where clause
user> (sql/as-sql (sql/where q (and {:foo 1} {:bar 1})))
"SELECT \"test\".\"foo\", \"test\".\"bar\" FROM \"test\" WHERE ((\"test\".\"foo\" = ?) AND (\"test\".\"bar\" = ?))"
;; One would have expected this to work, since we're essentially putting the same form into "where" macro:
user> (def clause '(and {:foo 1} {:bar 1}))
#'user/clause
user> (sql/as-sql (sql/where q clause))
"SELECT \"test\".\"foo\", \"test\".\"bar\" FROM \"test\" WHERE (and {:foo 1} {:bar 1})"
;; But unfortunately, it doesn't parse the form as it should
;; But wait! There's a solution, and it is to use fully qualified predicate functions from korma.sql.engine, just like this
user> (require '[korma.sql.fns :as sql.fns])
nil
user> (def clause '(sql.fns/pred-and {:foo 1} {:bar 2}))
#'user/clause
user> q
{:group [], :from [{:table "test"}], :joins [], :where [], :ent {:table "test"}, :type :select, :alias nil, :options nil, :fields [:foo :bar], :results :results, :table "test", :order [], :modifiers [], :db nil, :aliases #{}}
user> (sql/as-sql (sql/where q clause))
"SELECT \"test\".\"foo\", \"test\".\"bar\" FROM \"test\" WHERE (sql.engine/pred-and {:foo 1} {:bar 2})"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment