clojuresqlkorma

Missing FROM-clause entry for table?


When I select a specific field from a table in a has-many relationship I get an exception like this: org.postgresql.util.PSQLException: ERROR: missing FROM-clause entry for table \"bar\"

Here are the relationships I have defined:

(declare foo bar)

(korma/defentity foo
                 (korma/pk :token)
                 (korma/database db)
                 (korma/table :foo)
                 (korma/has-many bar {:fk :token}))

(korma/defentity bar
                 (korma/pk :token)
                 (korma/database db)
                 (korma/table :bar)
                 (korma/belongs-to foo {:fk :token}))

Here is the query I am generating in sqlkorma:

(defn fetch []
  (->
    (korma/select* foo)
    (korma/with bar)
    (korma/fields :foo.token :bar.col)
    (korma/exec)))

If I select all the fields using with * then the query runs with no problem. However, I would like to specify which fields I want to select, what am I doing wrong?


Solution

  • Think, I was passing the bar.col field in the wrong place. I guess because this is a has-many relationship, sql korma has to go away and run n+1 queries here. This explains why I see a missing FROM-clause exception, because I was telling sql korma to fetch a field in the wrong query.

    (defn fetch []
      (->
        (korma/select* foo)
        (korma/fields :token)
        (korma/with bar (korma/fields :col))
        (korma/exec)))