fukamachi / mito

An ORM for Common Lisp with migrations, relationships and PostgreSQL support
292 stars 31 forks source link

Allow to specify SELECT expression in select-dao #126

Closed kisp closed 1 year ago

kisp commented 1 year ago

Hi, thank you for this wonderful library!

Currently, the SELECT expression in mito:select-dao is hardcoded to :*. I am wondering, would it be a good to idea to allow this to be specified by the caller?

Then, you could write this form

(mito:select-dao 'item
  ...)

also like this

(mito:select-dao ('item :*)
  ...)

or like this

(mito:select-dao ('item :select :*)
  ...)

I will give you an example, where I would need this functionality.

Let's say I am working on this query:

(mito:select-dao 'item
  (sxql:join :item_relation :on (:= :item.id :item_relation.object_id))
  (sxql:join (:as :item :parent) :on (:= :parent.id :item_relation.subject_id))
  (sxql:where (:= :item.clarify_status "next-actions"))
  (sxql:where (:= :parent.clarify_status "project"))
  (sxql:order-by :item.id))

This works, but the problem is that it can return duplicate items, because of the joins.

Now, it would be possible to add a (sxql:group-by :item.id) to remove the duplicates.

But I cannot do this, because the SELECT expression then needs to be :item.*.

I would like to be able to write something like this:

(mito:select-dao ('item :item.*)
  ...)

What do you think about adding this possibility? Any other thoughts? Thanks! :)

kisp commented 1 year ago

I managed to write my query like this:

(mito.dao:select-by-sql
 'item
 (sxql:select :item.*
   (sxql:from :item)
   (sxql:join :item_relation :on (:= :item.id :item_relation.object_id))
   (sxql:join (:as :item :parent) :on (:= :parent.id :item_relation.subject_id))
   (sxql:where (:= :item.clarify_status "next-actions"))
   (sxql:where (:= :parent.clarify_status "project"))
   (sxql:group-by :item.id)
   (sxql:order-by :item.id)))

So, probably this is good enough and this issue can be closed.

Should this function be exported, so that you can write mito:select-by-sql?

vindarel commented 1 year ago

Thanks for the follow-up. Exporting this function seems a good idea to me, and Eitaro might merge an easy change.

fukamachi commented 1 year ago

Sorry, I'm late to come here. You found a workaround, fortunately, and it also looks good to me. I feel it may be natural that select-dao also allows sxql:fields.