datascript

Immutable database and Datalog query engine for Clojure, ClojureScript and JS
oly 2020-08-24T10:20:57.008200Z

I want todo a count on the number of prices in a database, this works fine using (count ?prices) except when there are none then I get no data returned from the query how can i handle this so 0 is returned ?

oly 2020-08-25T08:44:17.010300Z

(d/q '[:find ?e ?i ?n ?slug  (count ?eid2)
                :keys eid id product/name product/slug ?prices
                :in $ ?product-id
                :where
                [?e :product/id ?i]
                [?eid2 :price/product ?prices]
                [?e :product/name ?n]
                [?e :product/slug ?slug]] @conn product-id)

oly 2020-08-25T08:45:02.010500Z

That's what i currently have, I can split it out in this situation but Its something that would be good to know how to achieve

pithyless 2020-08-27T08:50:24.013800Z

Is that ?eid2 supposed to fetch all prices in the DB? It doesn't seem to be related to any other clause in the query. If so, I'd just do a separate query for it (queries are cheap, don't need to join them into one big one). Otherwise, if you want to fetch something that may or may not exist (but want to ensure it's absence does not remove it from the result set), you want to pull that info, not query it. A pull would work like a maybe, but a where clause works like a must.

pithyless 2020-08-27T08:51:44.014700Z

You can also consider, if this kind of aggregate should not be done as a separate query (or even just using the indexes directly, if it's a simple relationship).

pithyless 2020-08-27T08:52:36.014900Z

And just a friendly reminder: whenever working with aggregates, don't forget to ask yourself if you need :with to make sure the results are accurate. (If you're aggregating on eids, this won't be an issue).

cjsauer 2020-08-24T13:49:15.009500Z

Not sure how to achieve that within the query itself, but you could wrap the query in an or expression: (or (my-query db) 0)

oly 2020-08-24T15:26:37.009700Z

I think the issue with that is the query returns multiple fields, I always want the other fields only the aggregate to be 0 and not remove the other data

oly 2020-08-24T15:26:55.009900Z

unless you mean i can use the or in the middle of the where conditions ?

cjsauer 2020-08-24T17:50:56.010100Z

Ah I think I misunderstood your original question. Could you post an example of the query?