Selecting from the results of a function taking arguments

22 views
Skip to first unread message

Juho Vähä-Herttua

unread,
Feb 26, 2015, 12:46:07 PM2/26/15
to sqlk...@googlegroups.com
Consider I have a function that takes two arguments, user_id and address_id, and returns one or more rows. Then I have the following specification in my foo.clj:

(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.

Juho Vähä-Herttua

unread,
Feb 26, 2015, 3:44:04 PM2/26/15
to sqlk...@googlegroups.com
Ok, I thought I wouldn't have time to work on this today, but I had some time after all.

Created a pull request at https://github.com/korma/Korma/pull/283 and confirmed it fixes the issue I had. Didn't create a test case for this, because it would have required creating a new namespace just for the function that would return the dynamically created entity. I can do it though if you want to have it. We can move the discussion to GitHub.


Juho
Reply all
Reply to author
Forward
0 new messages