1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
// SPDX-License-Identifier: BUSL-1.1
//! PointUpdate: read-modify-write field-level changes to a single document.
//!
//! Each assignment is either a pre-encoded literal (fast binary merge when
//! possible) or a `SqlExpr` that must be evaluated against the *current* row —
//! the evaluator is `nodedb_query::expr::SqlExpr::eval`, shared with
//! computed-column, window, and typeguard paths.
use tracing::debug;
use crate::bridge::envelope::{ErrorCode, Response};
use crate::data::executor::core_loop::CoreLoop;
use crate::data::executor::doc_format;
use crate::data::executor::handlers::returning_rows;
use crate::data::executor::task::ExecutionTask;
use crate::engine::document::store::surrogate_to_doc_id;
use nodedb_physical::physical_plan::{ReturningSpec, UpdateValue};
use nodedb_types::Surrogate;
impl CoreLoop {
#[allow(clippy::too_many_arguments)]
pub(in crate::data::executor) fn execute_point_update(
&mut self,
task: &ExecutionTask,
tid: u64,
collection: &str,
document_id: &str,
surrogate: Surrogate,
updates: &[(String, UpdateValue)],
returning: Option<&ReturningSpec>,
) -> Response {
let row_key = surrogate_to_doc_id(surrogate);
let row_key = row_key.as_str();
debug!(
core = self.core_id,
%collection,
%document_id,
fields = updates.len(),
has_returning = returning.is_some(),
"point update"
);
let config_key = (crate::types::TenantId::new(tid), collection.to_string());
let is_strict = self.doc_configs.get(&config_key).is_some_and(|c| {
matches!(
c.storage_mode,
nodedb_physical::physical_plan::StorageMode::Strict { .. }
)
});
// Reject direct updates to generated columns.
if let Some(config) = self.doc_configs.get(&config_key)
&& let Err(e) = super::super::generated::check_generated_readonly(
updates,
&config.enforcement.generated_columns,
)
{
return self.response_error(task, e);
}
// Any non-literal assignment forces the slow decode→eval→re-encode path,
// because we need the current document to evaluate against.
let has_expr = updates
.iter()
.any(|(_, v)| matches!(v, UpdateValue::Expr(_)));
let bitemporal = self.is_bitemporal(tid, collection);
let sys_from_for_encode = if bitemporal {
self.bitemporal_now_ms()
} else {
0
};
let get_result = if bitemporal {
self.sparse.versioned_get_current(tid, collection, row_key)
} else {
self.sparse.get(tid, collection, row_key)
};
match get_result {
Ok(Some(current_bytes)) => {
let has_generated = self.doc_configs.get(&config_key).is_some_and(|c| {
!c.enforcement.generated_columns.is_empty()
&& super::super::generated::needs_recomputation(
updates,
&c.enforcement.generated_columns,
)
});
// Fast path: non-strict, no generated columns, all literal — merge at binary level.
let updated_bytes = if !is_strict && !has_generated && !has_expr {
let base_mp = doc_format::json_to_msgpack(¤t_bytes);
let update_pairs: Vec<(&str, &[u8])> = updates
.iter()
.filter_map(|(field, v)| match v {
UpdateValue::Literal(bytes) => Some((field.as_str(), bytes.as_slice())),
UpdateValue::Expr(_) => None,
})
.collect();
nodedb_query::msgpack_scan::merge_fields(&base_mp, &update_pairs)
} else {
// Strict, generated, or expression RHS: decode → mutate → re-encode.
let mut doc = if is_strict {
if let Some(config) = self.doc_configs.get(&config_key)
&& let nodedb_physical::physical_plan::StorageMode::Strict {
ref schema,
} = config.storage_mode
{
match super::super::super::strict_format::binary_tuple_to_json(
¤t_bytes,
schema,
) {
Some(v) => v,
None => {
return self.response_error(
task,
ErrorCode::Internal {
detail: "failed to decode Binary Tuple for update"
.into(),
},
);
}
}
} else {
return self.response_error(
task,
ErrorCode::Internal {
detail: "strict config missing during update".into(),
},
);
}
} else {
match doc_format::decode_document(¤t_bytes) {
Some(v) => v,
None => {
return self.response_error(
task,
ErrorCode::Internal {
detail: "failed to parse document for update".into(),
},
);
}
}
};
// Apply field-level updates. Expressions are evaluated
// against the current-row snapshot, so a later assignment
// observing a column updated earlier in the same statement
// still sees the pre-update value — matches PostgreSQL.
let eval_doc: nodedb_types::Value = doc.clone().into();
if let Some(obj) = doc.as_object_mut() {
for (field, update_val) in updates {
let val = match update_val {
UpdateValue::Literal(bytes) => {
match nodedb_types::json_from_msgpack(bytes) {
Ok(v) => v,
Err(e) => {
return self.response_error(
task,
ErrorCode::Internal {
detail: format!(
"update field '{field}': msgpack decode: {e}"
),
},
);
}
}
}
UpdateValue::Expr(expr) => {
let result: nodedb_types::Value = expr.eval(&eval_doc);
// Convert nodedb_types::Value → serde_json::Value so the
// downstream re-encode path (strict or msgpack) can proceed
// through its existing json-based branches unchanged.
let json: serde_json::Value = result.into();
json
}
};
obj.insert(field.clone(), val);
}
}
// Recompute generated columns.
if has_generated
&& let Some(config) = self.doc_configs.get(&config_key)
&& let Err(e) = super::super::generated::evaluate_generated_columns(
&mut doc,
&config.enforcement.generated_columns,
)
{
return self.response_error(task, e);
}
// Re-encode.
if is_strict {
if let Some(config) = self.doc_configs.get(&config_key)
&& let nodedb_physical::physical_plan::StorageMode::Strict {
ref schema,
} = config.storage_mode
{
let ndb_val: nodedb_types::Value = doc.clone().into();
let result = if bitemporal && schema.bitemporal {
super::super::super::strict_format::value_to_binary_tuple_bitemporal(
&ndb_val,
schema,
sys_from_for_encode,
i64::MIN,
i64::MAX,
)
} else {
super::super::super::strict_format::value_to_binary_tuple(
&ndb_val, schema,
)
};
match result {
Ok(bytes) => bytes,
Err(e) => {
return self.response_error(
task,
ErrorCode::Internal {
detail: format!("strict re-encode: {e}"),
},
);
}
}
} else {
return self.response_error(
task,
ErrorCode::Internal {
detail: "strict config missing during re-encode".into(),
},
);
}
} else {
doc_format::encode_to_msgpack(&doc)
}
};
let write_result = if bitemporal {
self.sparse
.versioned_put(crate::engine::sparse::btree_versioned::VersionedPut {
tenant: tid,
coll: collection,
doc_id: row_key,
sys_from_ms: sys_from_for_encode,
valid_from_ms: i64::MIN,
valid_until_ms: i64::MAX,
body: &updated_bytes,
})
.map(|()| None::<Vec<u8>>)
} else {
self.sparse.put(tid, collection, row_key, &updated_bytes)
};
match write_result {
Ok(_prior) => {
self.doc_cache.put(
task.request.database_id.as_u64(),
tid,
collection,
row_key,
&updated_bytes,
);
// Emit update event to Event Plane. `current_bytes`
// is the pre-update row already read above; the
// helper derives `WriteOp::Update` from the Some
// prior + Some new pair and handles strict→msgpack
// conversion on both sides.
self.emit_put_event(
task,
tid,
collection,
row_key,
&updated_bytes,
Some(¤t_bytes),
);
if let Some(spec) = returning {
// Build the post-update document with id injected.
let with_id = nodedb_query::msgpack_scan::inject_str_field(
&updated_bytes,
"id",
document_id,
);
let doc = match doc_format::decode_document(&with_id) {
Some(v) => v,
None => serde_json::json!({"id": document_id}),
};
match returning_rows::build_rows_payload(spec, &[doc]) {
Ok(payload) => self.response_with_payload(task, payload),
Err(e) => self.response_error(
task,
ErrorCode::Internal {
detail: format!("RETURNING encode: {e}"),
},
),
}
} else {
let mut payload = Vec::with_capacity(16);
nodedb_query::msgpack_scan::write_map_header(&mut payload, 1);
nodedb_query::msgpack_scan::write_kv_i64(&mut payload, "affected", 1);
self.response_with_payload(task, payload)
}
}
Err(e) => self.response_error(
task,
ErrorCode::Internal {
detail: e.to_string(),
},
),
}
}
Ok(None) => {
let mut payload = Vec::with_capacity(16);
nodedb_query::msgpack_scan::write_map_header(&mut payload, 1);
nodedb_query::msgpack_scan::write_kv_i64(&mut payload, "affected", 0);
self.response_with_payload(task, payload)
}
Err(e) => self.response_error(
task,
ErrorCode::Internal {
detail: e.to_string(),
},
),
}
}
}