Matthew Boston

Setting null values in Datomic

April 21, 2014

Key takeaway: To empty a field in Datomic, retract the fact that holds its current value.

You can’t set a value to null in Datomic. To clear a field, you retract the fact that it had a value. If you try nil, you get this:

IllegalArgumentExceptionInfo :db.error/nil-value Nil is not a legal value  datomic.error/arg (error.clj:55)

It took me a few moments to see why. Datomic’s docs on immutable values say there are only two possibilities: a value is present, or a value is not present yet. An entity either has a value for an attribute or it doesn’t have the attribute at all.

So when John removes his last name, you retract “Smith”:

(datomic/transact conn [[:db/retract 17592186045418
                         :user/lastname "Smith"]])

Now the entity is {:db/id 17592186045418, :user/firstname "John"}. Same entity, with :user/lastname retracted.

A form submit can’t hardcode the old value, so we build the retractions from the existing entity and the empty fields in the new one:

(defn- has-empty-value? [[k v]]
  (empty? (str v)))

(defn- keys-for-empty-vals
  "Get a list of keys from a map which have empty values."
  [m]
  (keys (filter has-empty-value? m)))

(defn- retract-statement
  "Only build a retract statement for existing values."
  [old-entity k]
  (let [v (get old-entity k)]
    (when v
      [:db/retract (:db/id old-entity) k v])))

(defn retracted-fields
  "Get all retractions from an existing entity."
  [old-entity new-entity]
  (filterv identity (map (partial retract-statement old-entity)
                         (keys-for-empty-vals new-entity))))

It finds the keys with empty values, builds a [:db/retract eid key val] for each, and drops the ones that had nothing to retract. Combine its output with the non-empty fields and pass the whole vector to datomic/transact.

Nothing in it is specific to users, so we moved it into its own namespace and reuse it for the next entity that needs a field cleared: (retractions/retracted-fields old-car new-car).