Skip to content

Instantly share code, notes, and snippets.

@vvvvalvalval
Created February 23, 2017 10:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vvvvalvalval/4f1736fab9b4ab0e3e03b805ad35a78c to your computer and use it in GitHub Desktop.
Save vvvvalvalval/4f1736fab9b4ab0e3e03b805ad35a78c to your computer and use it in GitHub Desktop.
datomic-fu
{:db/ident :bsu.fns/reset-to-many-by,
:db/doc "Resets the set of entities which are related to `eid` via `ref-attr` to the set given by `val-maps`.
Assumptions:
* `ref-attr` is a cardinality-many, ref attribute.
* `e` is an entity identifier for an _existing_ entity
(you have to know whether an entity exists before using this function,
and it's pointless to use it on a non-existing entity as opposed to just asserting all the new values.)
* `val-maps` is a seq of transaction maps, all of which have the `v-id-attr` key provided.
* `retract-target-entity?`: whether to call :db.fn/retractEntity on the old entities which get removed from the relationship.
* the old values of the relationship all have the `id-attr` attribute."
:db/id #db/id[:db.part/user],
:db/fn #db/fn{:lang :clojure,
:imports [],
:requires [[datomic.api :as d]],
:params [db e ref-attr v-id-attr retract-target-entity? val-maps],
:code (let [v-id-attr (d/ident db v-id-attr)
ref-attr (d/ident db ref-attr)
ent (d/entity db e)
new-ids (into #{} (map v-id-attr) val-maps)]
(into
[{:db/id e, ref-attr val-maps}]
(comp
(map v-id-attr)
(remove new-ids)
(map (fn [id]
(if retract-target-entity?
[:db.fn/retractEntity [v-id-attr id]]
[:db/retract e ref-attr [v-id-attr id]])
)))
(get ent ref-attr))
)}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment