korma / Korma

Tasty SQL for Clojure.
http://sqlkorma.com
1.48k stars 222 forks source link

Quoting of WHERE and JOIN clauses incorrect if no current DB specified during definition #212

Open thirteen37 opened 10 years ago

thirteen37 commented 10 years ago

I'm using a bunch of similar entities and queries on different MySQL databases, so I define the entities and queries up front, set the current DB, then execute these queries. E.g.,

(defentity some-table
           (belongs-to other-table))

(def find-things
     (-> (select* some-table)
         (with other-table)
         (where {:some-column 123})))

(default-connection (create-db (mysql {:host "192.168.1.1"})))
(-> find-things as-sql)

This will end up misquoting the JOIN ON clause with double-quotes instead of backquote. If I move the default-connection to the top, this works as expected.

immoh commented 10 years ago

I'm sure you already know this but one workaround for this is to build queries as late as possible. For example here you could change find-things into a function:

(defn find-things []
  (-> (select* some-table)
      (with other-table)
      (where {:some-column 123})))

(-> (find-things) as-sql)

I've been also looking how to fix but it seems like it requires quite a lot of work to get this working.

mangr3n commented 7 years ago

Building complex entities out of subqueries becomes almost impossible then.

The only reason it's been working in my system is that I was doing live code reloading, so the connection existed when I built my entities...

ls4f commented 7 years ago

The db options are a fun subject (even I have a reverted patch along those lines). Assuming you aren't using different databases - changing the defaults(not setting a default db, but changing the default rules) first thing in the namespace is a viable workaround.

mangr3n commented 7 years ago

I added this code to the top of the file defining all of my entities...

(defdb empty (mysql {:db "mysql"}))

the offending string was precomputed and present in (-> index-documents :table :korma.sql.utils/sub :sql-str)