(defentity addresses)
(defentity users-to-addresses
(belongs-to addresses {:fk :address_id}))
(defentity users
(has-many users-to-addresses {:fk :user_id}))
(defn link-address [userid addressid]
(-> (create-entity users-to-addresses)
(table (sqlfn link_address userid addressid) :users-to-addresses)
(belongs-to addresses {:fk :address_id})))
If I start my repl and include this with simply (use 'foo) I get following results:
=> (sql-only (select users-to-addresses (with addresses)))
"SELECT \"users-to-addresses\".*, \"addresses\".* FROM \"users-to-addresses\" LEFT JOIN \"addresses\" ON \"addresses\".\"id\" = \"users-to-addresses\".\"address_id\""
=> (sql-only (select (link-address 1 1) (with addresses)))
"SELECT \"users-to-addresses\".*, \"addresses\".* FROM LINK_ADDRESS(?, ?) AS \"users-to-addresses\" LEFT JOIN \"addresses\" ON \"addresses\".\"id\" = \"users-to-addresses\".\"address_id\""
This is exactly what I want, even though the implementation of link-address feels slightly ugly. However when I try to do the same on the repl by using (require '[foo :as foo]) I get something else instead:
=> (sql-only (select foo/users-to-addresses (with foo/addresses)))
"SELECT \"users-to-addresses\".*, \"addresses\".* FROM \"users-to-addresses\" LEFT JOIN \"addresses\" ON \"addresses\".\"id\" = \"users-to-addresses\".\"address_id\""
=> (sql-only (select (foo/link-address 1 1) (with foo/addresses)))
Exception Entity used in relationship does not exist: addresses korma.core/rel/fn--3183 (core.clj:563)
So the problem seems to be that addresses is resolved in the wrong namespace when create-entity is used as I am using it. I checked the korma.core/rel definition and I don't quite understand it. Why does it try to resolve the sub-ent in *ns* instead of (-> sub-ent meta :ns)? Because my understanding is that (deref sub-ent) will use the latter namespace...
I'd just like to confirm if this is a bug or not, before I start working on a patch. Now I'm working around this with raw SQL, but would be nicer to do this with Korma.