korma / Korma

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

subquery behaves weirdly when composed #143

Open andykitchen opened 11 years ago

andykitchen commented 11 years ago
;; This works
(select (subselect table (where (= :a :b))))

;; However is not the same as
(select (where (subselect table) (= :a :b))))

;; You need to so something like this using a select*
(select (subselect (where (select* table) (= :a :b)))))

In the given example, the second form causes the where clause to be silently dropped. There should at least be some kind of error message. Perhaps this is just one of the confusing corners of subselect being more like select than select*. Is there some way to improve the api to make this less confusing?

andykitchen commented 11 years ago

One suggestion would be to add a "subquery" wrapper, and maybe even remove subselect and only have subquery:

(select (subquery (select table (where (= :a :b)))))

This makes things a lot more uniform and composable. Then select queries don't need to know if they are going to be used in a subselect or not. Here is an example usage:

(defn premium-members []
  (select members
    (fields :id)
    (where {:premium true})))

(defn premium-members-posts []
  (select posts
    (where {:member_id [in (subquery (premium-members))]})))

Kind Regards

AK

AlexBaranosky commented 11 years ago

The second is not correct usage of the DSL.

On Tue, Apr 9, 2013 at 12:12 AM, Andy Kitchen notifications@github.comwrote:

;; This works(select (subselect table (where (= :a :b)))) ;; However is not the same as(select (where (subselect table) (= :a b))))

In the given example, the second form causes the where clause to be dropped.

— Reply to this email directly or view it on GitHubhttps://github.com/korma/Korma/issues/143 .

AlexBaranosky commented 11 years ago

If you're looking to compose queries, first look at select* and the * family of functions.

On Tue, Apr 9, 2013 at 1:08 AM, Alex Baranosky < alexander.baranosky@gmail.com> wrote:

The second is not correct usage of the DSL.

On Tue, Apr 9, 2013 at 12:12 AM, Andy Kitchen notifications@github.comwrote:

;; This works(select (subselect table (where (= :a :b)))) ;; However is not the same as(select (where (subselect table) (= :a b))))

In the given example, the second form causes the where clause to be dropped.

— Reply to this email directly or view it on GitHubhttps://github.com/korma/Korma/issues/143 .

andykitchen commented 11 years ago

Thanks @AlexBaranosky, I indeed do use select* in the third example. I think the problem with the second is that there is no error message and the where clause is silently ignored. I think that the API would also be more uniform with the "subquery" function.