tonsky / datascript

Immutable database and Datalog query engine for Clojure, ClojureScript and JS
Eclipse Public License 1.0
5.46k stars 304 forks source link

Can you set cardinality on a reversed attribute? #414

Closed uriva closed 2 years ago

uriva commented 2 years ago

Let's say you have book and author and you decided to model it as :author/book. Because an author can have many books, the cardinality would be :db.cardinality/many. However when you run the reversed query, each book has exactly one author, but pull queries would return a collection, even though there should only be one. Is there a way to avoid this?

tonsky commented 2 years ago

Yes and no. If you mark :author/book as component (:db/isComponent true), it will start to work this way. Be aware, though, that causes some other effects too: e.g. if you delete the author all the books will be deleted recursively. Also, pull/entity will automatically pull books when you pull the author.

Please note that components are not validated to have single reverse arity, it is just assumed that you will never transact data that will contradict that.

I personally don’t like components (they bring variation where you don’t expect it) and never really use them, but that means I have to (first) each reverse ref.

See details here https://docs.datomic.com/on-prem/schema/schema.html#component

uriva commented 2 years ago

Thank you!