korma / Korma

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

Fields behaviour prevents distinct on particular fields from working #286

Closed afandian closed 6 years ago

afandian commented 9 years ago

This shares some features with issue #251 .

I have a table my-table which I normally want to select all fields a, b, c, d from.

(k/defentity my-table (k/entity-fields :a :b :c :d))

Now I want to find distinct :a and :bs: SELECT distinct a, b FROM my_table;

(k/select my-table
      (k/modifier "DISTINCT")
      (k/fields :a :b))

But this doesn't work because I can't restrict my fields.

(k/sql-only (k/select my-table (k/fields :a :b)
                               (k/modifier "DISTINCT")))

"SELECT DISTINCT `my-table`.`a`,
                 `my-table`.`b`,
                 `my-table`.`c`,
                 `my-table`.`d`,
                 `my-table`.`a`,
                 `my-table`.`b` FROM `my-table`"

Notice the repeated a and b.

I think the suggested behaviour is to remove c and d from defentity, but they are standard fields that should be in the defentity and I don't want to have to re-write every other query to put the fields back in.

It seems like Korma doesn't allow me to write this query. Have I understood this correctly? My alternatives are a separate defentity, which feels like the wrong thing to do, or to write SQL.

immoh commented 9 years ago

Entity fields defined for entity are always included which means you need to either change the entity definition or not use the entity for this query. You can use the table name (as keyword), no need to define entity for it:

(k/select :my-table
      (k/modifier "DISTINCT")
      (k/fields :a :b))
venantius commented 6 years ago

As this is expected behavior and no further comment has been made, I'm going to close this issue.