Skip to main content

relate_executor/overlay/
writes.rs

1//! The write verbs: every overlay mutation (`create_node`, `create_rel`,
2//! `add_labels`/`remove_labels`, the `set_property_*` /
3//! `merge_properties_*` / `replace_properties_*` family, `delete_*`)
4//! funnels through [`WriteScratch::push_redo`], so the redo log and the
5//! lazy equality indexes stay current for every write. Stats accounting
6//! (creates, deletes, properties set/removed, net label deltas) happens
7//! here, next to the mutation it counts: the openCypher graph-diff
8//! counters (net new label names, property set/removed pairs) and Neo4j's
9//! update counters beside them (labels per node, one property write per
10//! write, ADR-0309).
11
12use std::collections::{BTreeMap, HashSet};
13
14use relate_core::{Node, NodeId, RelId, Relationship, Result, Value};
15use relate_ir::Direction;
16
17use crate::graph::{EntityId, Graph};
18use crate::redo::RedoOp;
19
20use super::label_probe::LabelChange;
21use super::{distinct_labels, ExecGraph, WriteScratch};
22
23impl ExecGraph<'_> {
24    pub fn create_node(
25        &self,
26        labels: Vec<String>,
27        properties: BTreeMap<String, Value>,
28    ) -> Result<NodeId> {
29        let mut s = self.scratch_mut();
30        let labels = std::sync::Arc::new(labels);
31        let properties = std::sync::Arc::new(relate_core::PropertyMap::from(properties));
32        let (labels_added, labels_removed) = self.label_deltas(&s, &labels, LabelChange::Gain);
33        s.reserve_new_node(&Node {
34            id: 0,
35            labels: std::sync::Arc::clone(&labels),
36            properties: std::sync::Arc::clone(&properties),
37        })?;
38        let id = s.alloc_node()?;
39        s.statement.stats.nodes_created += 1;
40        s.net_label_stats(labels_added, labels_removed);
41        s.statement.stats.properties_set += properties.len() as i64;
42        s.batch.nodes.insert(
43            id,
44            Node {
45                id,
46                labels: std::sync::Arc::clone(&labels),
47                properties: std::sync::Arc::clone(&properties),
48            },
49        );
50        s.batch.bump_live_labels(&labels, 1);
51        s.push_redo(RedoOp::CreateNode {
52            id,
53            labels,
54            properties,
55        });
56        drop(s);
57        relate_core::tokens::poll()?;
58        Ok(id)
59    }
60
61    pub fn create_rel(
62        &self,
63        start: NodeId,
64        end: NodeId,
65        rel_type: String,
66        properties: BTreeMap<String, Value>,
67    ) -> Result<RelId> {
68        if !self.node_exists(start) || !self.node_exists(end) {
69            return Err(crate::graph::missing_rel_endpoint_error());
70        }
71        let properties = std::sync::Arc::new(relate_core::PropertyMap::from(properties));
72        let mut s = self.scratch_mut();
73        s.reserve_new_rel(&Relationship {
74            id: 0,
75            start,
76            end,
77            rel_type: rel_type.clone(),
78            properties: std::sync::Arc::clone(&properties),
79        })?;
80        let id = s.alloc_rel()?;
81        s.statement.stats.relationships_created += 1;
82        s.statement.stats.properties_set += properties.len() as i64;
83        s.batch.rels.insert(
84            id,
85            Relationship {
86                id,
87                start,
88                end,
89                rel_type: rel_type.clone(),
90                properties: std::sync::Arc::clone(&properties),
91            },
92        );
93        s.batch.out_adj.entry(start).or_default().push(id);
94        s.batch.in_adj.entry(end).or_default().push(id);
95        s.push_redo(RedoOp::CreateRel {
96            id,
97            start,
98            end,
99            rel_type,
100            properties,
101        });
102        drop(s);
103        relate_core::tokens::poll()?;
104        Ok(id)
105    }
106
107    fn cow_node<'b>(s: &'b mut WriteScratch, base: &Graph, id: NodeId) -> Option<&'b mut Node> {
108        if s.batch.deleted_nodes.contains(&id) {
109            return None;
110        }
111        if !s.batch.nodes.contains_key(&id) {
112            let n = base.node_at(id, s.snapshot_ts())?;
113            // LABS-1085 review: a copy-on-write introduces the base node
114            // into the scratch, so its whole label/property vocabulary
115            // posts into the equality index — exactly what a create
116            // posts. Without this, a pair built before the cow misses
117            // the node's pre-existing properties, and a keyed lookup
118            // (MERGE's match arm) silently misses the node and creates
119            // a duplicate. Set/label ops on the copy post on top;
120            // postings are sets, so a double post is harmless.
121            for (key, value) in &*n.properties {
122                s.batch.prop_ix.post_value(id, &n.labels, key, value);
123            }
124            s.batch.nodes.insert(id, n);
125        }
126        s.batch.nodes.get_mut(&id)
127    }
128
129    fn cow_rel<'b>(
130        s: &'b mut WriteScratch,
131        base: &Graph,
132        id: RelId,
133    ) -> Option<&'b mut Relationship> {
134        if s.batch.deleted_rels.contains(&id) {
135            return None;
136        }
137        if !s.batch.rels.contains_key(&id) {
138            let r = base.rel_at(id, s.snapshot_ts())?;
139            // The node cow's posting contract (above), on the rel index.
140            for (key, value) in &*r.properties {
141                s.batch.rel_prop_ix.post_value(id, &r.rel_type, key, value);
142            }
143            s.batch.rels.insert(id, r);
144        }
145        s.batch.rels.get_mut(&id)
146    }
147
148    pub fn add_labels(&self, id: NodeId, labels: &[String]) {
149        if labels.is_empty() {
150            return;
151        }
152        let existing = self.node_labels(id).unwrap_or_default();
153        // The labels this write actually adds: the distinct requested labels
154        // not already on the node, in first-occurrence order. Computed once
155        // and reused for the accounting and the cow block; `n.labels ==
156        // existing` at cow time, so the cow block pushes `fresh` as-is
157        // instead of re-answering the membership question per label.
158        let fresh: Vec<String> = distinct_labels(labels)
159            .into_iter()
160            .filter(|l| !existing.iter().any(|x| x == *l))
161            .map(str::to_string)
162            .collect();
163        let mut s = self.scratch_mut();
164        let created = s.batch.created_nodes.contains(&id);
165        let shift = CreatedShift::begin(&s, created, node_label_bytes(id));
166        let mut added = Vec::new();
167        if let Some(n) = Self::cow_node(&mut s, self.base, id) {
168            std::sync::Arc::make_mut(&mut n.labels).extend(fresh.iter().cloned());
169            added = fresh;
170        }
171        shift.finish(&mut s);
172        // Accounted from the applied set (`added`), like remove_labels: a
173        // missing or scratch-deleted node applies nothing and counts nothing.
174        let (labels_added, labels_removed) = self.label_deltas(&s, &added, LabelChange::Gain);
175        s.net_label_stats(labels_added, labels_removed);
176        if !added.is_empty() {
177            s.batch.bump_live_labels(&added, 1);
178            s.push_redo(RedoOp::add_labels(id, added));
179        }
180    }
181
182    pub fn remove_labels(&self, id: NodeId, labels: &[String]) {
183        // Cow the node first and derive everything from `n.labels` in one
184        // pass: `extract_if` walks the node's labels once, dropping the
185        // ones the request names and collecting them into `actually` in
186        // node order. `requested` answers membership in O(1) per node
187        // label; `actually` feeds the accounting and the live-label bump
188        // (both consumers dedupe, so node order is as good as request
189        // order). A missing or scratch-deleted node leaves `actually`
190        // empty, exactly what the pre-cow read answered for it.
191        let requested: HashSet<&str> = labels.iter().map(String::as_str).collect();
192        let mut s = self.scratch_mut();
193        let created = s.batch.created_nodes.contains(&id);
194        let shift = CreatedShift::begin(&s, created, node_label_bytes(id));
195        let mut actually: Vec<String> = Vec::new();
196        if let Some(n) = Self::cow_node(&mut s, self.base, id) {
197            actually = std::sync::Arc::make_mut(&mut n.labels)
198                .extract_if(.., |l| requested.contains(l.as_str()))
199                .collect();
200        }
201        shift.finish(&mut s);
202        let (labels_added, labels_removed) = self.label_deltas(&s, &actually, LabelChange::Loss);
203        s.net_label_stats(labels_added, labels_removed);
204        if !actually.is_empty() {
205            s.batch.bump_live_labels(&actually, -1);
206            // The op carries the labels the node actually lost, so the
207            // ADR-0309 per-node count is derived from it (a requested label
208            // the node did not carry is a no-op).
209            s.push_redo(RedoOp::remove_labels(id, actually));
210        }
211    }
212
213    /// CIP-162 overwrite semantics, spelled once beside the primitives it
214    /// composes: the node's labels become exactly `labels` — the ones it
215    /// carries but the list omits leave ([`remove_labels`]), then the
216    /// list's labels arrive ([`add_labels`]). Each half keeps its own
217    /// accounting and redo, so the overwrite is their compose, not a third
218    /// label-write path.
219    pub fn set_labels(&self, id: NodeId, labels: &[String]) {
220        let current = self.node_labels(id).unwrap_or_default();
221        let remove: Vec<String> = current
222            .into_iter()
223            .filter(|label| !labels.contains(label))
224            .collect();
225        // An empty diff skips the remove half (mirroring add_labels' own
226        // empty-list guard) instead of cowing the node for nothing.
227        if !remove.is_empty() {
228            self.remove_labels(id, &remove);
229        }
230        self.add_labels(id, labels);
231    }
232
233    pub fn set_property_node(&self, id: NodeId, key: &str, value: Value) {
234        let mut s = self.scratch_mut();
235        let created = s.batch.created_nodes.contains(&id);
236        let shift = CreatedShift::begin(&s, created, node_property_bytes(id));
237        let outcome = Self::cow_node(&mut s, self.base, id).map(|n| {
238            set_prop_core(
239                std::sync::Arc::make_mut(&mut n.properties),
240                created,
241                key,
242                &value,
243            )
244        });
245        shift.finish(&mut s);
246        finish_set_property(&mut s, outcome, |op| match op {
247            PropOpKind::Set(k, v) => RedoOp::set_node_prop(id, k, v),
248            PropOpKind::Remove(k) => RedoOp::remove_node_prop(id, k),
249        });
250    }
251
252    pub fn set_property_rel(&self, id: RelId, key: &str, value: Value) {
253        let mut s = self.scratch_mut();
254        let created = s.batch.created_rels.contains(&id);
255        let shift = CreatedShift::begin(&s, created, rel_property_bytes(id));
256        let outcome = Self::cow_rel(&mut s, self.base, id).map(|r| {
257            set_prop_core(
258                std::sync::Arc::make_mut(&mut r.properties),
259                created,
260                key,
261                &value,
262            )
263        });
264        shift.finish(&mut s);
265        finish_set_property(&mut s, outcome, |op| match op {
266            PropOpKind::Set(k, v) => RedoOp::set_rel_prop(id, k, v),
267            PropOpKind::Remove(k) => RedoOp::remove_rel_prop(id, k),
268        });
269    }
270
271    /// `SET n += map`: per-key merge through the set verb (an existing
272    /// key keeps its position, a new one is added) — the node and
273    /// relationship forms are the same loop over their set verbs.
274    pub fn merge_properties_node(&self, id: NodeId, map: &BTreeMap<String, Value>) {
275        for (k, v) in map {
276            self.set_property_node(id, k, v.clone());
277        }
278    }
279
280    /// The relationship form of [`Self::merge_properties_node`].
281    pub fn merge_properties_rel(&self, id: RelId, map: &BTreeMap<String, Value>) {
282        for (k, v) in map {
283            self.set_property_rel(id, k, v.clone());
284        }
285    }
286
287    pub fn replace_properties_node(&self, id: NodeId, map: BTreeMap<String, Value>) {
288        let keys: Vec<String> = self
289            .node(id)
290            .map(|n| n.properties.keys().cloned().collect())
291            .unwrap_or_default();
292        replace_props(keys, map, |k, v| self.set_property_node(id, k, v));
293    }
294
295    pub fn replace_properties_rel(&self, id: RelId, map: BTreeMap<String, Value>) {
296        let keys: Vec<String> = self
297            .rel(id)
298            .map(|r| r.properties.keys().cloned().collect())
299            .unwrap_or_default();
300        replace_props(keys, map, |k, v| self.set_property_rel(id, k, v));
301    }
302
303    /// The kind-addressed forms of the three property verbs a resolved
304    /// write drives: the `EntityId` selector lives here once, so no write
305    /// arm re-opens a `match entity { Node => …_node, Rel => …_rel }` of
306    /// its own.
307    pub(crate) fn set_property(&self, entity: EntityId, key: &str, value: Value) {
308        match entity {
309            EntityId::Node(id) => self.set_property_node(id, key, value),
310            EntityId::Rel(id) => self.set_property_rel(id, key, value),
311        }
312    }
313
314    /// [`Self::set_property`]'s full-replacement form.
315    pub(crate) fn replace_properties(&self, entity: EntityId, map: BTreeMap<String, Value>) {
316        match entity {
317            EntityId::Node(id) => self.replace_properties_node(id, map),
318            EntityId::Rel(id) => self.replace_properties_rel(id, map),
319        }
320    }
321
322    /// [`Self::set_property`]'s per-key merge form.
323    pub(crate) fn merge_properties(&self, entity: EntityId, map: &BTreeMap<String, Value>) {
324        match entity {
325            EntityId::Node(id) => self.merge_properties_node(id, map),
326            EntityId::Rel(id) => self.merge_properties_rel(id, map),
327        }
328    }
329
330    pub fn delete_rel(&self, id: RelId) {
331        // One fetch answers both "is the rel live" and "what it carries":
332        // a missing rel has nothing to delete (the `let … else` twin of
333        // `delete_node`'s form).
334        let Some(r) = self.rel(id) else { return };
335        let nprops = r.properties.len() as i64;
336        let mut s = self.scratch_mut();
337        release_created(&mut s, EntityId::Rel(id));
338        s.batch.deleted_rels.insert(id);
339        net_or_count_delete(&mut s, EntityId::Rel(id), nprops);
340        s.push_redo(RedoOp::delete_rel(id));
341    }
342
343    pub fn delete_node(&self, id: NodeId, detach: bool) -> Result<()> {
344        let incident: Vec<RelId> = self.neighbors(id, Direction::Both);
345        if !detach && !incident.is_empty() {
346            return Err(crate::graph::delete_connected_node_error());
347        }
348        for rid in &incident {
349            self.delete_rel(*rid);
350        }
351        // One fetch answers both "is the node live" and "what does it
352        // carry": a missing node has nothing to delete.
353        let Some(node) = self.node(id) else {
354            return Ok(());
355        };
356        let nprops = node.properties.len() as i64;
357        let labels = node.labels;
358        let mut s = self.scratch_mut();
359        let (labels_added, labels_removed) = self.label_deltas(&s, &labels, LabelChange::Loss);
360        release_created(&mut s, EntityId::Node(id));
361        s.batch.deleted_nodes.insert(id);
362        s.batch.bump_live_labels(&labels, -1);
363        s.net_label_stats(labels_added, labels_removed);
364        net_or_count_delete(&mut s, EntityId::Node(id), nprops);
365        s.push_redo(RedoOp::delete_node(id));
366        Ok(())
367    }
368}
369
370/// The per-kind state one delete nets against (REL8-1188): the statement-local
371/// created set's verdict plus the four counter targets the decision writes.
372/// One bundle per kind, so the node/rel vocabulary is dispatched exactly once.
373struct DeleteNets<'a> {
374    statement_created: bool,
375    created: &'a mut i64,
376    set: &'a mut i64,
377    deleted: &'a mut i64,
378    removed: &'a mut i64,
379}
380
381/// The net-or-count decision both delete verbs share (REL8-1188). A delete
382/// nets the create's counters only for an entity *this statement* created in
383/// the batch it is deleting in — the id is still in the statement-local
384/// created set, which a batch rebase clears together with the batch's own
385/// charged created set ([`WriteScratch::rebase`]) — so a create/delete pair
386/// inside one statement cancels (the pinned
387/// `create_then_delete_cancels_create_stats` model). Every other delete
388/// counts as this statement's delete: of a pre-existing entity, of one an
389/// earlier statement of the transaction created (the create was counted by
390/// that statement, so netting here would drive the counter negative and
391/// poison every binding through the wire-stats boundary), or of one an
392/// earlier batch of this batched statement already committed
393/// (`CALL { … } IN TRANSACTIONS`, ADR-0210 — the committed create and the
394/// delete both report).
395fn net_or_count_delete(s: &mut WriteScratch, entity: EntityId, nprops: i64) {
396    let nets = match entity {
397        EntityId::Node(id) => DeleteNets {
398            statement_created: s.statement.created_nodes.remove(&id),
399            created: &mut s.statement.stats.nodes_created,
400            set: &mut s.statement.stats.properties_set,
401            deleted: &mut s.statement.stats.nodes_deleted,
402            removed: &mut s.statement.stats.properties_removed,
403        },
404        EntityId::Rel(id) => DeleteNets {
405            statement_created: s.statement.created_rels.remove(&id),
406            created: &mut s.statement.stats.relationships_created,
407            set: &mut s.statement.stats.properties_set,
408            deleted: &mut s.statement.stats.relationships_deleted,
409            removed: &mut s.statement.stats.properties_removed,
410        },
411    };
412    if nets.statement_created {
413        // The statement counted this create, so both counters still hold it:
414        // every property the entity carries was counted at the create or by a
415        // later write. `checked_sub` + the named expect keep a broken
416        // statement-created fact from the silent `saturating_sub` clamp that
417        // was the REL8-1188 bug; the i64 floor is refused here, and
418        // non-negativity is tripped where it is owned — the wire boundary's
419        // own expect (`relate::query_stats_to_wire`).
420        *nets.created = nets
421            .created
422            .checked_sub(1)
423            .expect("a statement-created entity's create counter still holds it");
424        *nets.set = nets
425            .set
426            .checked_sub(nprops)
427            .expect("a statement-created entity's property counter still holds it");
428    } else {
429        *nets.deleted += 1;
430        *nets.removed += nprops;
431    }
432}
433
434/// The workspace bytes the created node `id`'s labels hold now, `None`
435/// when the scratch has no copy of it.
436fn node_label_bytes(id: NodeId) -> impl Fn(&WriteScratch) -> Option<u64> {
437    move |s| {
438        s.batch
439            .nodes
440            .get(&id)
441            .map(|node| crate::workspace::created_label_bytes(&node.labels))
442    }
443}
444
445/// The workspace bytes the created node `id`'s properties hold now.
446fn node_property_bytes(id: NodeId) -> impl Fn(&WriteScratch) -> Option<u64> {
447    move |s| {
448        s.batch
449            .nodes
450            .get(&id)
451            .map(|node| crate::workspace::created_property_delta(&node.properties))
452    }
453}
454
455/// The workspace bytes the created relationship `id`'s properties hold now.
456fn rel_property_bytes(id: RelId) -> impl Fn(&WriteScratch) -> Option<u64> {
457    move |s| {
458        s.batch
459            .rels
460            .get(&id)
461            .map(|rel| crate::workspace::created_property_delta(&rel.properties))
462    }
463}
464
465/// The created-entity workspace shift as one guard: [`Self::begin`] snapshots
466/// the bytes `bytes` reads off the scratch copy (only when workspace
467/// accounting is on and the entity was created in this batch), and
468/// [`Self::finish`] re-reads them after the write and shifts the workspace
469/// by the difference. A snapshot exists only for an entity the scratch
470/// already held, and the cow never removes it.
471struct CreatedShift<F: Fn(&WriteScratch) -> Option<u64>> {
472    before: Option<u64>,
473    bytes: F,
474}
475
476impl<F: Fn(&WriteScratch) -> Option<u64>> CreatedShift<F> {
477    fn begin(s: &WriteScratch, created: bool, bytes: F) -> Self {
478        let before = if created && relate_core::tokens::workspace_accounting() {
479            bytes(s)
480        } else {
481            None
482        };
483        Self { before, bytes }
484    }
485
486    fn finish(self, s: &mut WriteScratch) {
487        let Some(before) = self.before else {
488            return;
489        };
490        let after = (self.bytes)(s).expect("the cow inserted the scratch copy");
491        s.shift_workspace(before, after);
492    }
493}
494
495/// The stats + redo tail `set_property_node`/`set_property_rel` share: fold
496/// the write's deltas into the statement stats and push the redo op the
497/// caller's constructor builds from the payload.
498fn finish_set_property(
499    s: &mut WriteScratch,
500    outcome: Option<PropWrite>,
501    redo: impl FnOnce(PropOpKind) -> RedoOp,
502) {
503    // A missing or scratch-deleted entity (no cow copy) is a no-op write.
504    let Some(PropWrite { set, removed, op }) = outcome else {
505        return;
506    };
507    s.statement.stats.properties_set += set;
508    s.statement.stats.properties_removed += removed;
509    if let Some(op) = op {
510        s.push_redo(redo(op));
511    }
512}
513
514/// The bookkeeping half of one delete, dispatched once per kind on
515/// [`EntityId`] (the same vocabulary [`net_or_count_delete`] reads): drop
516/// the entity's batch-set membership and take its scratch copy out — both
517/// unconditional, so the charged set never retains a deleted id — then
518/// release the copy's workspace charge when this batch created it. The
519/// write direction of the same charge is the `CreatedShift` pair beside
520/// this; a pre-existing entity's copy (a copy-on-write edit) was never
521/// charged as a create, so its delete releases nothing.
522fn release_created(s: &mut WriteScratch, entity: EntityId) {
523    match entity {
524        EntityId::Node(id) => {
525            let batch_created = s.batch.created_nodes.remove(&id);
526            let copy = s.batch.nodes.remove(&id);
527            let remaining = s.batch.created_nodes.len();
528            release_created_charge(s, batch_created, copy, |node| {
529                crate::workspace::created_node_remove_delta(remaining, node)
530            });
531        }
532        EntityId::Rel(id) => {
533            let batch_created = s.batch.created_rels.remove(&id);
534            let copy = s.batch.rels.remove(&id);
535            let remaining = s.batch.created_rels.len();
536            release_created_charge(s, batch_created, copy, |rel| {
537                crate::workspace::created_rel_remove_delta(remaining, rel)
538            });
539        }
540    }
541}
542
543/// The shared tail of [`release_created`]: a copy this batch created is
544/// charged with its own bytes plus one created-set slot, so its delete
545/// releases exactly that, priced against the set's post-removal size. A
546/// copy this batch did not create (a copy-on-write copy of a pre-existing
547/// entity) releases nothing. A created entity's copy is asserted live in
548/// every configuration, accounting off included; the priced release
549/// itself runs only while the workspace ledger is on.
550fn release_created_charge<T>(
551    s: &mut WriteScratch,
552    batch_created: bool,
553    copy: Option<T>,
554    delta: impl FnOnce(&T) -> u64,
555) {
556    if !batch_created {
557        return;
558    }
559    let copy = copy.expect("a batch-created entity's copy is live in the scratch");
560    if !relate_core::tokens::workspace_accounting() {
561        return;
562    }
563    s.shift_workspace(delta(&copy), 0);
564}
565
566/// The redo-op payload of one set_property, before the node/rel verb wraps
567/// it into its [`RedoOp`] variant.
568enum PropOpKind {
569    Set(String, Value),
570    Remove(String),
571}
572
573/// What one set_property did: the stats deltas plus the redo-op payload.
574#[derive(Default)]
575struct PropWrite {
576    set: i64,
577    removed: i64,
578    op: Option<PropOpKind>,
579}
580
581/// The shared core of `set_property_node`/`set_property_rel`: apply the
582/// null-means-remove / otherwise-upsert contract to one properties map and
583/// report the stats deltas plus the redo-op payload. A null value removing
584/// an absent key is a no-op (no deltas, no op).
585fn set_prop_core(
586    props: &mut relate_core::PropertyMap,
587    created: bool,
588    key: &str,
589    value: &Value,
590) -> PropWrite {
591    if value.is_null() {
592        if props.remove(key).is_some() {
593            return PropWrite {
594                set: 0,
595                removed: 1,
596                op: Some(PropOpKind::Remove(key.to_string())),
597            };
598        }
599        return PropWrite::default();
600    }
601    let existed = props.contains_key(key);
602    props.insert(key.to_string(), value.clone());
603    let (set, removed) = prop_stat_deltas(existed, created);
604    PropWrite {
605        set,
606        removed,
607        op: Some(PropOpKind::Set(key.to_string(), value.clone())),
608    }
609}
610
611/// The shared core of `replace_properties_*`: null out every current key the
612/// map does not name, then set every entry, all through the one setter.
613fn replace_props(
614    keys: Vec<String>,
615    map: BTreeMap<String, Value>,
616    mut set: impl FnMut(&str, Value),
617) {
618    for k in &keys {
619        if !map.contains_key(k) {
620            set(k, Value::Null);
621        }
622    }
623    for (k, v) in map {
624        set(&k, v);
625    }
626}
627
628/// Stats deltas for a set_property on a pre-existing (or CREATE-added) map:
629/// overwriting an existing key counts set+removed; a fresh key counts set;
630/// CREATE already counting the key (`created` on an `existed` map cell) is
631/// the no-op.
632fn prop_stat_deltas(existed: bool, created: bool) -> (i64, i64) {
633    if existed && !created {
634        (1, 1)
635    } else if !existed {
636        (1, 0)
637    } else {
638        (0, 0)
639    }
640}