1use std::collections::HashMap;
2
3use crate::application::entity::{
4 AppliedEntityMutation, CreateDocumentInput, CreateKvInput, CreateTimeSeriesPointInput,
5 RowUpdateColumnRule, RowUpdateContractPlan,
6};
7use crate::application::ttl_payload::{
8 has_internal_ttl_metadata, normalize_ttl_patch_operations, parse_top_level_ttl_metadata_entries,
9};
10use crate::json::{to_vec as json_to_vec, Value as JsonValue};
11use crate::storage::query::resolve_declared_data_type;
12use crate::storage::schema::{coerce as coerce_schema_value, DataType, Value};
13use crate::storage::unified::MetadataValue;
14
15use super::*;
16
17const TREE_METADATA_PREFIX: &str = "red.tree.";
18const TREE_CHILD_EDGE_LABEL: &str = "TREE_CHILD";
19
20fn apply_collection_default_ttl(
21 db: &crate::storage::unified::devx::RedDB,
22 collection: &str,
23 metadata: &mut Vec<(String, MetadataValue)>,
24) {
25 if has_internal_ttl_metadata(metadata) {
26 return;
27 }
28
29 let Some(default_ttl_ms) = db.collection_default_ttl_ms(collection) else {
30 return;
31 };
32
33 metadata.push((
34 "_ttl_ms".to_string(),
35 if default_ttl_ms <= i64::MAX as u64 {
36 MetadataValue::Int(default_ttl_ms as i64)
37 } else {
38 MetadataValue::Timestamp(default_ttl_ms)
39 },
40 ));
41}
42
43fn refresh_context_index(
44 db: &crate::storage::unified::devx::RedDB,
45 collection: &str,
46 id: crate::storage::EntityId,
47) -> RedDBResult<()> {
48 let store = db.store();
49 let Some(entity) = store.get(collection, id) else {
50 return Ok(());
51 };
52
53 store.context_index().index_entity(collection, &entity);
54 Ok(())
55}
56
57pub(crate) fn entity_row_fields_snapshot(
63 entity: &crate::storage::UnifiedEntity,
64) -> Vec<(String, Value)> {
65 let crate::storage::EntityData::Row(row) = &entity.data else {
66 return Vec::new();
67 };
68 let mut fields = if let Some(named) = &row.named {
69 named.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
70 } else if let Some(schema) = &row.schema {
71 schema
72 .iter()
73 .zip(row.columns.iter())
74 .map(|(name, value)| (name.clone(), value.clone()))
75 .collect()
76 } else {
77 Vec::new()
78 };
79 expand_binary_document_body_snapshot(&mut fields);
80 fields
81}
82
83fn expand_binary_document_body_snapshot(fields: &mut Vec<(String, Value)>) {
84 let Some(body_idx) = fields.iter().position(|(name, _)| name == "body") else {
85 return;
86 };
87 let Value::Json(bytes) = &fields[body_idx].1 else {
88 return;
89 };
90 let body_fields = crate::document_body::body_fields(bytes);
91 if let Some(body_json) = crate::document_body::decode_container_to_json(bytes) {
92 if let Ok(json_bytes) = crate::json::to_vec(&body_json) {
93 fields[body_idx].1 = Value::Json(json_bytes);
94 }
95 }
96 let Some(body_fields) = body_fields else {
97 return;
98 };
99 for (name, value) in body_fields {
100 if fields.iter().all(|(existing, _)| existing != &name) {
101 fields.push((name, value));
102 }
103 }
104}
105
106fn ensure_collection_model_contract(
107 db: &crate::storage::unified::devx::RedDB,
108 collection: &str,
109 requested_model: crate::catalog::CollectionModel,
110) -> RedDBResult<()> {
111 if let Some(contract) = db.collection_contract(collection) {
112 if !contract_enforces_model(&contract) {
113 return Ok(());
114 }
115 if collection_model_allows(contract.declared_model, requested_model) {
116 return Ok(());
117 }
118 if requested_model == crate::catalog::CollectionModel::Vector
125 && contract
126 .ai_policy
127 .as_ref()
128 .is_some_and(|policy| policy.embed.is_some() || policy.vision.is_some())
129 {
130 return Ok(());
131 }
132 return Err(crate::RedDBError::InvalidOperation(format!(
133 "collection '{}' is declared as '{}' and does not allow '{}' writes",
134 collection,
135 collection_model_name(contract.declared_model),
136 collection_model_name(requested_model)
137 )));
138 }
139
140 let now = implicit_contract_unix_ms();
141 db.save_collection_contract(crate::physical::CollectionContract {
142 name: collection.to_string(),
143 declared_model: requested_model,
144 schema_mode: crate::catalog::SchemaMode::Dynamic,
145 origin: crate::physical::ContractOrigin::Implicit,
146 version: 1,
147 created_at_unix_ms: now,
148 updated_at_unix_ms: now,
149 default_ttl_ms: db.collection_default_ttl_ms(collection),
150 vector_dimension: None,
151 vector_metric: None,
152 context_index_fields: Vec::new(),
153 declared_columns: Vec::new(),
154 table_def: matches!(requested_model, crate::catalog::CollectionModel::Table)
155 .then(|| crate::storage::schema::TableDef::new(collection.to_string())),
156 timestamps_enabled: false,
157 context_index_enabled: false,
158 metrics_raw_retention_ms: None,
159 metrics_rollup_policies: Vec::new(),
160 metrics_tenant_identity: None,
161 metrics_namespace: None,
162 append_only: false,
165 subscriptions: Vec::new(),
166 analytics_config: Vec::new(),
167 session_key: None,
168 session_gap_ms: None,
169 retention_duration_ms: None,
170 analytical_storage: None,
171
172 ai_policy: None,
173 })
174 .map(|_| ())
175 .map_err(|err| crate::RedDBError::Internal(err.to_string()))
176}
177
178fn implicit_contract_unix_ms() -> u128 {
179 std::time::SystemTime::now()
180 .duration_since(std::time::UNIX_EPOCH)
181 .unwrap_or_default()
182 .as_millis()
183}
184
185fn collection_model_allows(
186 declared_model: crate::catalog::CollectionModel,
187 requested_model: crate::catalog::CollectionModel,
188) -> bool {
189 declared_model == requested_model || declared_model == crate::catalog::CollectionModel::Mixed
190}
191
192fn ensure_vector_dimension_contract(
193 db: &crate::storage::unified::devx::RedDB,
194 collection: &str,
195 actual_dimension: usize,
196) -> RedDBResult<()> {
197 let Some(expected_dimension) = db
198 .collection_contract(collection)
199 .and_then(|contract| contract.vector_dimension)
200 else {
201 return Ok(());
202 };
203 if expected_dimension == actual_dimension {
204 return Ok(());
205 }
206 Err(crate::RedDBError::Query(format!(
207 "vector dimension mismatch for collection '{collection}': expected {expected_dimension}, got {actual_dimension}"
208 )))
209}
210
211fn collection_model_name(model: crate::catalog::CollectionModel) -> &'static str {
212 match model {
213 crate::catalog::CollectionModel::Table => "table",
214 crate::catalog::CollectionModel::Document => "document",
215 crate::catalog::CollectionModel::Graph => "graph",
216 crate::catalog::CollectionModel::Vector => "vector",
217 crate::catalog::CollectionModel::Hll => "hll",
218 crate::catalog::CollectionModel::Sketch => "sketch",
219 crate::catalog::CollectionModel::Filter => "filter",
220 crate::catalog::CollectionModel::Kv => "kv",
221 crate::catalog::CollectionModel::Config => "config",
222 crate::catalog::CollectionModel::Vault => "vault",
223 crate::catalog::CollectionModel::Mixed => "mixed",
224 crate::catalog::CollectionModel::TimeSeries => "timeseries",
225 crate::catalog::CollectionModel::Queue => "queue",
226 crate::catalog::CollectionModel::Metrics => "metrics",
227 }
228}
229
230#[derive(Clone)]
231struct UniquenessRule {
232 name: String,
233 columns: Vec<String>,
234 primary_key: bool,
235}
236
237#[derive(Copy, Clone, PartialEq, Eq)]
238enum NormalizeMode {
239 Insert,
243 Update,
247}
248
249mod collection_contract_enforcement {
250 use super::*;
251
252 pub(super) struct CollectionContractWriteEnforcer<'a> {
253 db: &'a crate::storage::unified::devx::RedDB,
254 collection: &'a str,
255 }
256
257 impl<'a> CollectionContractWriteEnforcer<'a> {
258 pub(super) fn new(
259 db: &'a crate::storage::unified::devx::RedDB,
260 collection: &'a str,
261 ) -> Self {
262 Self { db, collection }
263 }
264
265 pub(super) fn ensure_model(
266 &self,
267 requested_model: crate::catalog::CollectionModel,
268 ) -> RedDBResult<()> {
269 ensure_collection_model_contract(self.db, self.collection, requested_model)
270 }
271
272 pub(super) fn normalize_insert_fields(
273 &self,
274 fields: Vec<(String, Value)>,
275 ) -> RedDBResult<Vec<(String, Value)>> {
276 normalize_row_fields_for_contract_with_mode(
277 self.db,
278 self.collection,
279 fields,
280 NormalizeMode::Insert,
281 )
282 }
283
284 pub(super) fn normalize_update_fields(
285 &self,
286 fields: Vec<(String, Value)>,
287 ) -> RedDBResult<Vec<(String, Value)>> {
288 normalize_row_fields_for_contract_with_mode(
289 self.db,
290 self.collection,
291 fields,
292 NormalizeMode::Update,
293 )
294 }
295
296 pub(super) fn enforce_row_uniqueness(
297 &self,
298 fields: &[(String, Value)],
299 exclude_id: Option<crate::storage::EntityId>,
300 ) -> RedDBResult<()> {
301 enforce_row_uniqueness(self.db, self.collection, fields, exclude_id)
302 }
303
304 pub(super) fn enforce_batch_uniqueness(
305 &self,
306 rows: &[Vec<(String, Value)>],
307 ) -> RedDBResult<()> {
308 enforce_row_batch_uniqueness(self.db, self.collection, rows)
309 }
310
311 pub(super) fn requires_uniqueness_check(&self, modified_columns: &[String]) -> bool {
312 row_update_requires_uniqueness_check(self.db, self.collection, modified_columns)
313 }
314 }
315}
316
317use collection_contract_enforcement::CollectionContractWriteEnforcer;
318
319fn normalize_row_fields_for_contract_with_mode(
320 db: &crate::storage::unified::devx::RedDB,
321 collection: &str,
322 fields: Vec<(String, Value)>,
323 mode: NormalizeMode,
324) -> RedDBResult<Vec<(String, Value)>> {
325 let Some(contract) = db.collection_contract(collection) else {
326 return Ok(fields);
327 };
328
329 if contract.declared_model != crate::catalog::CollectionModel::Table
330 || (contract.declared_columns.is_empty()
331 && contract
332 .table_def
333 .as_ref()
334 .map(|table| table.columns.is_empty())
335 .unwrap_or(true))
336 {
337 return Ok(fields);
338 }
339
340 let existing_created_at = if contract.timestamps_enabled && mode == NormalizeMode::Update {
350 fields
351 .iter()
352 .find(|(n, _)| n == "created_at")
353 .map(|(_, v)| v.clone())
354 } else {
355 None
356 };
357
358 if contract.timestamps_enabled && mode == NormalizeMode::Insert {
363 for (name, _) in &fields {
364 if name == "created_at" || name == "updated_at" {
365 return Err(crate::RedDBError::Query(format!(
366 "collection '{}' manages '{}' automatically — do not set it in INSERT",
367 collection, name
368 )));
369 }
370 }
371 }
372
373 let mut provided = std::collections::BTreeMap::new();
374 for (name, value) in &fields {
375 provided.insert(name.clone(), value.clone());
376 }
377
378 let resolved_columns = resolved_contract_columns(&contract)?;
379 let declared_names: std::collections::BTreeSet<String> = resolved_columns
380 .iter()
381 .map(|column| column.name.clone())
382 .collect();
383 let unknown_fields: Vec<String> = fields
384 .iter()
385 .filter(|(name, _)| !declared_names.contains(name))
386 .map(|(name, _)| name.clone())
387 .collect();
388 if matches!(contract.schema_mode, crate::catalog::SchemaMode::Strict)
389 && !unknown_fields.is_empty()
390 {
391 return Err(crate::RedDBError::Query(format!(
392 "collection '{}' is strict and does not allow undeclared fields: {}",
393 collection,
394 unknown_fields.join(", ")
395 )));
396 }
397 let mut normalized = Vec::new();
398 let now_ms = current_unix_ms_u64();
399
400 for column in &resolved_columns {
401 match provided.remove(&column.name) {
402 Some(value) => {
403 if contract.timestamps_enabled && mode == NormalizeMode::Update {
408 match column.name.as_str() {
409 "created_at" => {
410 normalized.push((
411 column.name.clone(),
412 existing_created_at
413 .clone()
414 .unwrap_or(Value::UnsignedInteger(now_ms)),
415 ));
416 continue;
417 }
418 "updated_at" => {
419 normalized.push((column.name.clone(), Value::UnsignedInteger(now_ms)));
420 continue;
421 }
422 _ => {}
423 }
424 }
425 normalized.push((
426 column.name.clone(),
427 normalize_contract_value(collection, column, value)?,
428 ));
429 }
430 None => {
431 if contract.timestamps_enabled
435 && (column.name == "created_at" || column.name == "updated_at")
436 {
437 normalized.push((column.name.clone(), Value::UnsignedInteger(now_ms)));
438 continue;
439 }
440 if let Some(default) = &column.default {
441 normalized.push((
442 column.name.clone(),
443 coerce_contract_literal(collection, &column.name, column, default)?,
444 ));
445 } else if column.not_null {
446 return Err(crate::RedDBError::Query(format!(
447 "missing required column '{}' for collection '{}'",
448 column.name, collection
449 )));
450 }
451 }
452 }
453 }
454
455 for (name, value) in fields {
456 if !declared_names.contains(&name) {
457 normalized.push((name, value));
458 }
459 }
460
461 Ok(normalized)
462}
463
464fn current_unix_ms_u64() -> u64 {
465 std::time::SystemTime::now()
466 .duration_since(std::time::UNIX_EPOCH)
467 .map(|d| d.as_millis() as u64)
468 .unwrap_or(0)
469}
470
471fn enforce_row_uniqueness(
472 db: &crate::storage::unified::devx::RedDB,
473 collection: &str,
474 fields: &[(String, Value)],
475 exclude_id: Option<crate::storage::EntityId>,
476) -> RedDBResult<()> {
477 let Some(contract) = db.collection_contract(collection) else {
478 return Ok(());
479 };
480 if contract.declared_model != crate::catalog::CollectionModel::Table
481 && contract.declared_model != crate::catalog::CollectionModel::Mixed
482 {
483 return Ok(());
484 }
485
486 let rules = resolved_uniqueness_rules(&contract);
487 if rules.is_empty() {
488 return Ok(());
489 }
490
491 let store = db.store();
492 let Some(manager) = store.get_collection(collection) else {
493 return Ok(());
494 };
495
496 let input_fields: std::collections::BTreeMap<String, Value> = fields.iter().cloned().collect();
497
498 for rule in &rules {
499 let mut expected_signatures = Vec::new();
500 let mut skip_rule = false;
501
502 for column in &rule.columns {
503 match input_fields.get(column) {
504 Some(Value::Null) | None if rule.primary_key => {
505 return Err(crate::RedDBError::Query(format!(
506 "primary key '{}' in collection '{}' requires non-null column '{}'",
507 rule.name, collection, column
508 )))
509 }
510 Some(Value::Null) | None => {
511 skip_rule = true;
512 break;
513 }
514 Some(value) => {
515 expected_signatures.push((column.clone(), value_signature(value)));
516 }
517 }
518 }
519
520 if skip_rule {
521 continue;
522 }
523
524 for entity in manager.query_all(|_| true) {
525 if exclude_id.map(|id| id == entity.id).unwrap_or(false) {
526 continue;
527 }
528 let Some(existing_fields) = row_fields_from_entity(&entity) else {
529 continue;
530 };
531
532 let duplicate = expected_signatures.iter().all(|(column, expected)| {
533 existing_fields
534 .get(column)
535 .map(|value| value_signature(value) == *expected)
536 .unwrap_or(false)
537 });
538
539 if duplicate {
540 let qualifier = if rule.primary_key {
541 "primary key"
542 } else {
543 "unique constraint"
544 };
545 return Err(crate::RedDBError::Query(format!(
546 "{} '{}' violated on collection '{}' for columns [{}]",
547 qualifier,
548 rule.name,
549 collection,
550 rule.columns.join(", ")
551 )));
552 }
553 }
554 }
555
556 Ok(())
557}
558
559fn enforce_row_batch_uniqueness(
560 db: &crate::storage::unified::devx::RedDB,
561 collection: &str,
562 rows: &[Vec<(String, Value)>],
563) -> RedDBResult<()> {
564 let Some(contract) = db.collection_contract(collection) else {
565 return Ok(());
566 };
567 if contract.declared_model != crate::catalog::CollectionModel::Table
568 && contract.declared_model != crate::catalog::CollectionModel::Mixed
569 {
570 return Ok(());
571 }
572
573 let rules = resolved_uniqueness_rules(&contract);
574 if rules.is_empty() {
575 return Ok(());
576 }
577
578 for rule in &rules {
579 let mut seen = std::collections::HashMap::<String, usize>::new();
580 for (row_index, fields) in rows.iter().enumerate() {
581 let input_fields: std::collections::BTreeMap<String, Value> =
582 fields.iter().cloned().collect();
583 let mut signatures = Vec::new();
584 let mut skip_rule = false;
585
586 for column in &rule.columns {
587 match input_fields.get(column) {
588 Some(Value::Null) | None if rule.primary_key => {
589 return Err(crate::RedDBError::Query(format!(
590 "primary key '{}' in collection '{}' requires non-null column '{}'",
591 rule.name, collection, column
592 )))
593 }
594 Some(Value::Null) | None => {
595 skip_rule = true;
596 break;
597 }
598 Some(value) => signatures.push(format!("{column}={}", value_signature(value))),
599 }
600 }
601
602 if skip_rule {
603 continue;
604 }
605
606 let signature = signatures.join("|");
607 if let Some(previous_index) = seen.insert(signature, row_index) {
608 return Err(crate::RedDBError::Query(format!(
609 "batch insert violates uniqueness rule '{}' in collection '{}' between rows {} and {}",
610 rule.name,
611 collection,
612 previous_index + 1,
613 row_index + 1
614 )));
615 }
616 }
617 }
618
619 Ok(())
620}
621
622fn row_update_requires_uniqueness_check(
623 db: &crate::storage::unified::devx::RedDB,
624 collection: &str,
625 modified_columns: &[String],
626) -> bool {
627 if modified_columns.is_empty() {
628 return false;
629 }
630
631 let Some(contract) = db.collection_contract(collection) else {
632 return false;
633 };
634 if contract.declared_model != crate::catalog::CollectionModel::Table
635 && contract.declared_model != crate::catalog::CollectionModel::Mixed
636 {
637 return false;
638 }
639
640 let rules = resolved_uniqueness_rules(&contract);
641 if rules.is_empty() {
642 return false;
643 }
644
645 rules.iter().any(|rule| {
646 rule.columns.iter().any(|column| {
647 modified_columns
648 .iter()
649 .any(|modified| modified.eq_ignore_ascii_case(column))
650 })
651 })
652}
653
654pub(crate) fn build_row_update_contract_plan(
655 db: &crate::storage::unified::devx::RedDB,
656 collection: &str,
657) -> RedDBResult<Option<RowUpdateContractPlan>> {
658 let Some(contract) = db.collection_contract(collection) else {
659 return Ok(None);
660 };
661
662 let declared_rules = if contract.declared_model == crate::catalog::CollectionModel::Table
663 && !(contract.declared_columns.is_empty()
664 && contract
665 .table_def
666 .as_ref()
667 .map(|table| table.columns.is_empty())
668 .unwrap_or(true))
669 {
670 resolved_contract_columns(&contract)?
671 .into_iter()
672 .map(|rule| {
673 (
674 rule.name.clone(),
675 RowUpdateColumnRule {
676 name: rule.name,
677 data_type: rule.data_type,
678 data_type_name: rule.data_type_name,
679 not_null: rule.not_null,
680 enum_variants: rule.enum_variants,
681 },
682 )
683 })
684 .collect()
685 } else {
686 HashMap::new()
687 };
688
689 let unique_columns = if matches!(
690 contract.declared_model,
691 crate::catalog::CollectionModel::Table | crate::catalog::CollectionModel::Mixed
692 ) {
693 resolved_uniqueness_rules(&contract)
694 .into_iter()
695 .flat_map(|rule| rule.columns.into_iter())
696 .map(|column| (column, ()))
697 .collect()
698 } else {
699 HashMap::new()
700 };
701
702 Ok(Some(RowUpdateContractPlan {
703 timestamps_enabled: contract.timestamps_enabled,
704 strict_schema: matches!(contract.schema_mode, crate::catalog::SchemaMode::Strict),
705 declared_rules,
706 unique_columns,
707 }))
708}
709
710pub(crate) fn normalize_row_update_assignment_with_plan(
711 collection: &str,
712 column: &str,
713 value: Value,
714 row_contract_plan: Option<&RowUpdateContractPlan>,
715) -> RedDBResult<Value> {
716 let Some(plan) = row_contract_plan else {
717 return Ok(value);
718 };
719
720 if plan.timestamps_enabled && (column == "created_at" || column == "updated_at") {
721 return Err(crate::RedDBError::Query(format!(
722 "collection '{}' manages '{}' automatically — do not set it in UPDATE",
723 collection, column
724 )));
725 }
726
727 if let Some(rule) = plan.declared_rules.get(column) {
728 let rule = ResolvedColumnRule {
729 name: rule.name.clone(),
730 data_type: rule.data_type,
731 data_type_name: rule.data_type_name.clone(),
732 not_null: rule.not_null,
733 default: None,
734 enum_variants: rule.enum_variants.clone(),
735 };
736 normalize_contract_value(collection, &rule, value)
737 } else if plan.strict_schema {
738 Err(crate::RedDBError::Query(format!(
739 "collection '{}' is strict and does not allow undeclared fields: {}",
740 collection, column
741 )))
742 } else {
743 Ok(value)
744 }
745}
746
747pub(crate) fn normalize_row_update_value_for_rule(
748 collection: &str,
749 value: Value,
750 row_rule: Option<&RowUpdateColumnRule>,
751) -> RedDBResult<Value> {
752 let Some(rule) = row_rule else {
753 return Ok(value);
754 };
755
756 let rule = ResolvedColumnRule {
757 name: rule.name.clone(),
758 data_type: rule.data_type,
759 data_type_name: rule.data_type_name.clone(),
760 not_null: rule.not_null,
761 default: None,
762 enum_variants: rule.enum_variants.clone(),
763 };
764 normalize_contract_value(collection, &rule, value)
765}
766
767fn set_row_field(row: &mut crate::storage::unified::entity::RowData, name: &str, value: Value) {
768 if let Some(named) = row.named.as_mut() {
769 named.insert(name.to_string(), value);
770 return;
771 }
772
773 if let Some(schema) = row.schema.as_ref() {
774 if let Some(index) = schema.iter().position(|column| column == name) {
775 if let Some(slot) = row.columns.get_mut(index) {
776 *slot = value;
777 return;
778 }
779 }
780
781 let mut named = HashMap::with_capacity(schema.len().saturating_add(1));
782 for (column, current) in schema.iter().zip(row.columns.iter()) {
783 named.insert(column.clone(), current.clone());
784 }
785 named.insert(name.to_string(), value);
786 row.named = Some(named);
787 return;
788 }
789
790 let mut named = HashMap::with_capacity(1);
791 named.insert(name.to_string(), value);
792 row.named = Some(named);
793}
794
795fn collect_row_fields(row: &crate::storage::unified::entity::RowData) -> Vec<(String, Value)> {
796 if let Some(named) = row.named.as_ref() {
797 named
798 .iter()
799 .map(|(key, value)| (key.clone(), value.clone()))
800 .collect()
801 } else if let Some(schema) = row.schema.as_ref() {
802 schema
803 .iter()
804 .cloned()
805 .zip(row.columns.iter().cloned())
806 .collect()
807 } else {
808 Vec::new()
809 }
810}
811
812fn apply_row_field_assignments_raw<I>(
813 row: &mut crate::storage::unified::entity::RowData,
814 field_assignments: I,
815) where
816 I: IntoIterator<Item = (String, Value)>,
817{
818 for (column, value) in field_assignments {
819 set_row_field(row, &column, value);
820 }
821}
822
823fn apply_row_field_assignments_incremental<I>(
824 collection: &str,
825 row: &mut crate::storage::unified::entity::RowData,
826 field_assignments: I,
827 row_contract_plan: Option<&RowUpdateContractPlan>,
828) -> RedDBResult<()>
829where
830 I: IntoIterator<Item = (String, Value)>,
831{
832 for (column, value) in field_assignments {
833 let value = normalize_row_update_assignment_with_plan(
834 collection,
835 &column,
836 value,
837 row_contract_plan,
838 )?;
839
840 set_row_field(row, &column, value);
841 }
842
843 Ok(())
844}
845
846fn resolved_uniqueness_rules(
847 contract: &crate::physical::CollectionContract,
848) -> Vec<UniquenessRule> {
849 let mut rules = Vec::new();
850
851 if let Some(table_def) = &contract.table_def {
852 if !table_def.primary_key.is_empty() {
853 rules.push(UniquenessRule {
854 name: "primary_key".to_string(),
855 columns: table_def.primary_key.clone(),
856 primary_key: true,
857 });
858 }
859
860 for constraint in &table_def.constraints {
861 if matches!(
862 constraint.constraint_type,
863 crate::storage::schema::ConstraintType::PrimaryKey
864 ) && !constraint.columns.is_empty()
865 {
866 rules.push(UniquenessRule {
867 name: constraint.name.clone(),
868 columns: constraint.columns.clone(),
869 primary_key: true,
870 });
871 } else if matches!(
872 constraint.constraint_type,
873 crate::storage::schema::ConstraintType::Unique
874 ) && !constraint.columns.is_empty()
875 {
876 rules.push(UniquenessRule {
877 name: constraint.name.clone(),
878 columns: constraint.columns.clone(),
879 primary_key: false,
880 });
881 }
882 }
883 } else {
884 for column in &contract.declared_columns {
885 if column.primary_key {
886 rules.push(UniquenessRule {
887 name: format!("pk_{}", column.name),
888 columns: vec![column.name.clone()],
889 primary_key: true,
890 });
891 } else if column.unique {
892 rules.push(UniquenessRule {
893 name: format!("uniq_{}", column.name),
894 columns: vec![column.name.clone()],
895 primary_key: false,
896 });
897 }
898 }
899 }
900
901 let mut dedup = std::collections::BTreeSet::new();
902 rules
903 .into_iter()
904 .filter(|rule| dedup.insert((rule.primary_key, rule.columns.clone())))
905 .collect()
906}
907
908fn row_fields_from_entity(
909 entity: &crate::storage::UnifiedEntity,
910) -> Option<std::collections::BTreeMap<String, Value>> {
911 match &entity.data {
912 crate::storage::EntityData::Row(row) => {
913 if let Some(named) = &row.named {
914 Some(
915 named
916 .iter()
917 .map(|(key, value)| (key.clone(), value.clone()))
918 .collect(),
919 )
920 } else {
921 row.schema.as_ref().map(|schema| {
922 schema
923 .iter()
924 .cloned()
925 .zip(row.columns.iter().cloned())
926 .collect()
927 })
928 }
929 }
930 _ => None,
931 }
932}
933
934fn value_signature(value: &Value) -> String {
935 format!("{value:?}")
936}
937
938fn normalize_contract_value(
939 collection: &str,
940 column: &ResolvedColumnRule,
941 value: Value,
942) -> RedDBResult<Value> {
943 if matches!(value, Value::Null) {
944 if column.not_null {
945 return Err(crate::RedDBError::Query(format!(
946 "column '{}' in collection '{}' cannot be null",
947 column.name, collection
948 )));
949 }
950 return Ok(Value::Null);
951 }
952
953 let target = column.data_type;
954 if value_matches_declared_type(&value, target) {
955 return Ok(value);
956 }
957
958 let Some(raw) = value_to_coercion_input(&value) else {
959 return Err(crate::RedDBError::Query(format!(
960 "column '{}' in collection '{}' requires type '{}' but value cannot be coerced",
961 column.name, collection, column.data_type_name
962 )));
963 };
964
965 coerce_contract_literal(collection, &column.name, column, &raw)
966}
967
968fn coerce_contract_literal(
969 collection: &str,
970 column_name: &str,
971 column: &ResolvedColumnRule,
972 raw: &str,
973) -> RedDBResult<Value> {
974 let target = column.data_type;
975 match target {
976 DataType::Blob => Ok(Value::Blob(raw.as_bytes().to_vec())),
977 DataType::Json => Ok(Value::Json(raw.as_bytes().to_vec())),
978 DataType::Timestamp => raw.parse::<i64>().map(Value::Timestamp).map_err(|err| {
979 crate::RedDBError::Query(format!(
980 "failed to coerce column '{}' in collection '{}' to '{}': {}",
981 column_name, collection, column.data_type_name, err
982 ))
983 }),
984 DataType::Duration => raw.parse::<i64>().map(Value::Duration).map_err(|err| {
985 crate::RedDBError::Query(format!(
986 "failed to coerce column '{}' in collection '{}' to '{}': {}",
987 column_name, collection, column.data_type_name, err
988 ))
989 }),
990 DataType::Vector | DataType::Array => Err(crate::RedDBError::Query(format!(
991 "column '{}' in collection '{}' requires '{}' and only typed values are accepted for this type",
992 column_name, collection, column.data_type_name
993 ))),
994 _ => coerce_schema_value(raw, target, Some(column.enum_variants.as_slice())).map_err(
995 |err| {
996 crate::RedDBError::Query(format!(
997 "failed to coerce column '{}' in collection '{}' to '{}': {}",
998 column_name, collection, column.data_type_name, err
999 ))
1000 },
1001 ),
1002 }
1003}
1004
1005struct ResolvedColumnRule {
1006 name: String,
1007 data_type: DataType,
1008 data_type_name: String,
1009 not_null: bool,
1010 default: Option<String>,
1011 enum_variants: Vec<String>,
1012}
1013
1014fn resolved_contract_columns(
1015 contract: &crate::physical::CollectionContract,
1016) -> RedDBResult<Vec<ResolvedColumnRule>> {
1017 if let Some(table_def) = &contract.table_def {
1018 return Ok(table_def
1019 .columns
1020 .iter()
1021 .map(|column| ResolvedColumnRule {
1022 name: column.name.clone(),
1023 data_type: column.data_type,
1024 data_type_name: data_type_name(column.data_type).to_string(),
1025 not_null: !column.nullable,
1026 default: column
1027 .default
1028 .as_ref()
1029 .map(|bytes| String::from_utf8_lossy(bytes).to_string()),
1030 enum_variants: column.enum_variants.clone(),
1031 })
1032 .collect());
1033 }
1034
1035 contract
1036 .declared_columns
1037 .iter()
1038 .map(|column| {
1039 let data_type = column
1040 .sql_type
1041 .as_ref()
1042 .map(crate::storage::query::resolve_sql_type_name)
1043 .transpose()
1044 .map_err(|err| crate::RedDBError::Query(err.to_string()))?
1045 .unwrap_or(parse_declared_data_type(&column.data_type)?);
1046 Ok(ResolvedColumnRule {
1047 name: column.name.clone(),
1048 data_type,
1049 data_type_name: column.data_type.clone(),
1050 not_null: column.not_null,
1051 default: column.default.clone(),
1052 enum_variants: column.enum_variants.clone(),
1053 })
1054 })
1055 .collect()
1056}
1057
1058fn parse_declared_data_type(value: &str) -> RedDBResult<DataType> {
1059 resolve_declared_data_type(value).map_err(|err| crate::RedDBError::Query(err.to_string()))
1060}
1061
1062fn data_type_name(data_type: DataType) -> &'static str {
1063 match data_type {
1064 DataType::Integer => "integer",
1065 DataType::UnsignedInteger => "unsigned_integer",
1066 DataType::Float => "float",
1067 DataType::Text => "text",
1068 DataType::Blob => "blob",
1069 DataType::Boolean => "boolean",
1070 DataType::Timestamp => "timestamp",
1071 DataType::Duration => "duration",
1072 DataType::IpAddr => "ipaddr",
1073 DataType::MacAddr => "macaddr",
1074 DataType::Vector => "vector",
1075 DataType::Nullable => "nullable",
1076 DataType::Unknown => "unknown",
1077 DataType::Json => "json",
1078 DataType::Uuid => "uuid",
1079 DataType::NodeRef => "noderef",
1080 DataType::EdgeRef => "edgeref",
1081 DataType::VectorRef => "vectorref",
1082 DataType::RowRef => "rowref",
1083 DataType::Color => "color",
1084 DataType::Email => "email",
1085 DataType::Url => "url",
1086 DataType::Phone => "phone",
1087 DataType::Semver => "semver",
1088 DataType::Cidr => "cidr",
1089 DataType::Date => "date",
1090 DataType::Time => "time",
1091 DataType::Decimal => "decimal",
1092 DataType::Enum => "enum",
1093 DataType::Array => "array",
1094 DataType::TimestampMs => "timestamp_ms",
1095 DataType::Ipv4 => "ipv4",
1096 DataType::Ipv6 => "ipv6",
1097 DataType::Subnet => "subnet",
1098 DataType::Port => "port",
1099 DataType::Latitude => "latitude",
1100 DataType::Longitude => "longitude",
1101 DataType::GeoPoint => "geopoint",
1102 DataType::Country2 => "country2",
1103 DataType::Country3 => "country3",
1104 DataType::Lang2 => "lang2",
1105 DataType::Lang5 => "lang5",
1106 DataType::Currency => "currency",
1107 DataType::AssetCode => "asset_code",
1108 DataType::Money => "money",
1109 DataType::ColorAlpha => "color_alpha",
1110 DataType::BigInt => "bigint",
1111 DataType::KeyRef => "keyref",
1112 DataType::DocRef => "docref",
1113 DataType::TableRef => "tableref",
1114 DataType::PageRef => "pageref",
1115 DataType::Secret => "secret",
1116 DataType::Password => "password",
1117 DataType::TextZstd => "text",
1118 DataType::BlobZstd => "blob",
1119 }
1120}
1121
1122fn value_matches_declared_type(value: &Value, target: DataType) -> bool {
1123 matches!(
1124 (value, target),
1125 (Value::Null, _)
1126 | (Value::Integer(_), DataType::Integer)
1127 | (Value::UnsignedInteger(_), DataType::UnsignedInteger)
1128 | (Value::Float(_), DataType::Float)
1129 | (Value::Text(_), DataType::Text)
1130 | (Value::Blob(_), DataType::Blob)
1131 | (Value::Boolean(_), DataType::Boolean)
1132 | (Value::Timestamp(_), DataType::Timestamp)
1133 | (Value::Duration(_), DataType::Duration)
1134 | (Value::IpAddr(_), DataType::IpAddr)
1135 | (Value::MacAddr(_), DataType::MacAddr)
1136 | (Value::Vector(_), DataType::Vector)
1137 | (Value::Json(_), DataType::Json)
1138 | (Value::Uuid(_), DataType::Uuid)
1139 | (Value::NodeRef(_), DataType::NodeRef)
1140 | (Value::EdgeRef(_), DataType::EdgeRef)
1141 | (Value::VectorRef(_, _), DataType::VectorRef)
1142 | (Value::RowRef(_, _), DataType::RowRef)
1143 | (Value::Color(_), DataType::Color)
1144 | (Value::Email(_), DataType::Email)
1145 | (Value::Url(_), DataType::Url)
1146 | (Value::Phone(_), DataType::Phone)
1147 | (Value::Semver(_), DataType::Semver)
1148 | (Value::Cidr(_, _), DataType::Cidr)
1149 | (Value::Date(_), DataType::Date)
1150 | (Value::Time(_), DataType::Time)
1151 | (Value::Decimal(_), DataType::Decimal)
1152 | (Value::EnumValue(_), DataType::Enum)
1153 | (Value::Array(_), DataType::Array)
1154 | (Value::TimestampMs(_), DataType::TimestampMs)
1155 | (Value::Ipv4(_), DataType::Ipv4)
1156 | (Value::Ipv6(_), DataType::Ipv6)
1157 | (Value::Subnet(_, _), DataType::Subnet)
1158 | (Value::Port(_), DataType::Port)
1159 | (Value::Latitude(_), DataType::Latitude)
1160 | (Value::Longitude(_), DataType::Longitude)
1161 | (Value::GeoPoint(_, _), DataType::GeoPoint)
1162 | (Value::Country2(_), DataType::Country2)
1163 | (Value::Country3(_), DataType::Country3)
1164 | (Value::Lang2(_), DataType::Lang2)
1165 | (Value::Lang5(_), DataType::Lang5)
1166 | (Value::Currency(_), DataType::Currency)
1167 | (Value::ColorAlpha(_), DataType::ColorAlpha)
1168 | (Value::BigInt(_), DataType::BigInt)
1169 | (Value::KeyRef(_, _), DataType::KeyRef)
1170 | (Value::DocRef(_, _), DataType::DocRef)
1171 | (Value::TableRef(_), DataType::TableRef)
1172 | (Value::PageRef(_), DataType::PageRef)
1173 | (Value::Secret(_), DataType::Secret)
1174 | (Value::Password(_), DataType::Password)
1175 )
1176}
1177
1178fn value_to_coercion_input(value: &Value) -> Option<String> {
1179 match value {
1180 Value::Null => None,
1181 Value::Integer(value) => Some(value.to_string()),
1182 Value::UnsignedInteger(value) => Some(value.to_string()),
1183 Value::Float(value) => Some(value.to_string()),
1184 Value::Text(value) => Some(value.to_string()),
1185 Value::Blob(value) => String::from_utf8(value.clone()).ok(),
1186 Value::Boolean(value) => Some(value.to_string()),
1187 Value::Timestamp(value) => Some(value.to_string()),
1188 Value::Duration(value) => Some(value.to_string()),
1189 Value::IpAddr(value) => Some(value.to_string()),
1190 Value::MacAddr(value) => Some(format!(
1191 "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
1192 value[0], value[1], value[2], value[3], value[4], value[5]
1193 )),
1194 Value::Json(value) => Some(String::from_utf8_lossy(value).to_string()),
1195 Value::Email(value) => Some(value.clone()),
1196 Value::Url(value) => Some(value.clone()),
1197 Value::Phone(value) => Some(value.to_string()),
1198 Value::Semver(value) => Some(format!(
1199 "{}.{}.{}",
1200 value / 1_000_000,
1201 (value / 1_000) % 1_000,
1202 value % 1_000
1203 )),
1204 Value::Date(value) => Some(value.to_string()),
1205 Value::Time(value) => Some(value.to_string()),
1206 Value::Decimal(value) => Some(value.to_string()),
1207 Value::TimestampMs(value) => Some(value.to_string()),
1208 Value::Ipv4(value) => Some(format!(
1209 "{}.{}.{}.{}",
1210 (value >> 24) & 0xFF,
1211 (value >> 16) & 0xFF,
1212 (value >> 8) & 0xFF,
1213 value & 0xFF
1214 )),
1215 Value::Port(value) => Some(value.to_string()),
1216 Value::Latitude(value) => Some((*value as f64 / 1_000_000.0).to_string()),
1217 Value::Longitude(value) => Some((*value as f64 / 1_000_000.0).to_string()),
1218 Value::GeoPoint(lat, lon) => Some(format!(
1219 "{},{}",
1220 *lat as f64 / 1_000_000.0,
1221 *lon as f64 / 1_000_000.0
1222 )),
1223 Value::BigInt(value) => Some(value.to_string()),
1224 Value::TableRef(value) => Some(value.clone()),
1225 Value::PageRef(value) => Some(value.to_string()),
1226 Value::Password(value) => Some(value.clone()),
1227 _ => None,
1228 }
1229}
1230
1231fn dedupe_modified_columns(mut modified_columns: Vec<String>) -> Vec<String> {
1232 if modified_columns.is_empty() {
1233 return modified_columns;
1234 }
1235
1236 let mut unique = Vec::with_capacity(modified_columns.len());
1237 for column in modified_columns.drain(..) {
1238 if !unique
1239 .iter()
1240 .any(|existing: &String| existing.eq_ignore_ascii_case(&column))
1241 {
1242 unique.push(column);
1243 }
1244 }
1245 unique
1246}
1247
1248fn reject_document_array_position_path(path: &[String]) -> RedDBResult<()> {
1249 if path.iter().any(|segment| segment.parse::<usize>().is_ok()) {
1250 return Err(crate::RedDBError::Query(
1251 "array positional document patch paths are unsupported; replace the array or full document body instead"
1252 .to_string(),
1253 ));
1254 }
1255 Ok(())
1256}
1257
1258fn document_body_from_named(fields: &HashMap<String, Value>) -> RedDBResult<JsonValue> {
1259 match fields.get("body") {
1260 Some(Value::Json(bytes)) => {
1261 if let Some(body) = crate::document_body::decode_container_to_json(bytes) {
1264 Ok(body)
1265 } else {
1266 crate::json::from_slice(bytes).map_err(|err| {
1267 crate::RedDBError::Query(format!("failed to decode document body: {err}"))
1268 })
1269 }
1270 }
1271 Some(_) => Err(crate::RedDBError::Query(
1272 "document body field must contain JSON".to_string(),
1273 )),
1274 None => Ok(JsonValue::Object(Default::default())),
1275 }
1276}
1277
1278fn document_body_from_assignment(value: &Value) -> RedDBResult<JsonValue> {
1279 match value {
1280 Value::Json(bytes) | Value::Blob(bytes) => crate::json::from_slice(bytes)
1281 .map_err(|err| crate::RedDBError::Query(format!("invalid JSON body: {err}"))),
1282 Value::Text(text) => crate::json::from_str(text.as_ref())
1283 .map_err(|err| crate::RedDBError::Query(format!("invalid JSON body: {err}"))),
1284 Value::Integer(value) => crate::json::from_str(&value.to_string())
1285 .map_err(|err| crate::RedDBError::Query(format!("invalid JSON body: {err}"))),
1286 Value::UnsignedInteger(value) => crate::json::from_str(&value.to_string())
1287 .map_err(|err| crate::RedDBError::Query(format!("invalid JSON body: {err}"))),
1288 Value::Float(value) => crate::json::from_str(&value.to_string())
1289 .map_err(|err| crate::RedDBError::Query(format!("invalid JSON body: {err}"))),
1290 other => Err(crate::RedDBError::Query(format!(
1291 "column 'body' expected JSON body, got {other:?}"
1292 ))),
1293 }
1294}
1295
1296fn document_body_set_operation(column: &str, value: Value) -> PatchEntityOperation {
1297 PatchEntityOperation {
1298 op: PatchEntityOperationType::Set,
1299 path: column.split('.').map(str::to_string).collect(),
1300 value: Some(crate::presentation::entity_json::storage_value_to_json(
1301 &value,
1302 )),
1303 }
1304}
1305
1306fn replace_document_fields_body(
1307 fields: &mut HashMap<String, Value>,
1308 body: JsonValue,
1309 binary: bool,
1310 modified_columns: &mut Vec<String>,
1311) -> RedDBResult<()> {
1312 modified_columns.push("body".to_string());
1313
1314 let old_keys: Vec<String> = fields
1315 .keys()
1316 .filter(|key| key.as_str() != "body")
1317 .cloned()
1318 .collect();
1319 for key in old_keys {
1320 fields.remove(&key);
1321 modified_columns.push(key);
1322 }
1323
1324 let body_bytes = crate::document_body::serialize_document_body(&body, binary)?;
1325 fields.insert("body".to_string(), Value::Json(body_bytes));
1326
1327 Ok(())
1328}
1329
1330fn replace_document_row_body(
1331 row: &mut crate::storage::unified::entity::RowData,
1332 body: JsonValue,
1333 binary: bool,
1334 modified_columns: &mut Vec<String>,
1335) -> RedDBResult<()> {
1336 let fields = row.named.get_or_insert_with(Default::default);
1337 replace_document_fields_body(fields, body, binary, modified_columns)?;
1338
1339 row.columns.clear();
1343 row.schema = None;
1344 Ok(())
1345}
1346
1347fn document_merge_patch_payload(payload: &JsonValue) -> &JsonValue {
1348 if let JsonValue::Object(object) = payload {
1349 if object.len() == 1 {
1350 if let Some(body) = object.get("body") {
1351 return body;
1352 }
1353 }
1354 }
1355 payload
1356}
1357
1358fn apply_document_json_merge_patch(body: &mut JsonValue, patch: &JsonValue) -> RedDBResult<()> {
1359 if !matches!(patch, JsonValue::Object(_)) {
1360 *body = patch.clone();
1361 return Ok(());
1362 }
1363
1364 if matches!(patch, JsonValue::Object(object) if object.is_empty()) {
1365 if !matches!(body, JsonValue::Object(_)) {
1366 *body = JsonValue::Object(Default::default());
1367 }
1368 return Ok(());
1369 }
1370
1371 let mut operations = Vec::new();
1372 collect_document_json_merge_patch_operations(body, Vec::new(), patch, &mut operations);
1373 apply_patch_operations_to_json(body, &operations).map_err(crate::RedDBError::Query)
1374}
1375
1376fn collect_document_json_merge_patch_operations(
1377 target: &JsonValue,
1378 path: Vec<String>,
1379 patch: &JsonValue,
1380 operations: &mut Vec<PatchEntityOperation>,
1381) {
1382 let JsonValue::Object(patch_object) = patch else {
1383 operations.push(PatchEntityOperation {
1384 op: PatchEntityOperationType::Set,
1385 path,
1386 value: Some(patch.clone()),
1387 });
1388 return;
1389 };
1390
1391 for (key, value) in patch_object {
1392 let mut child_path = path.clone();
1393 child_path.push(key.clone());
1394 match value {
1395 JsonValue::Null => operations.push(PatchEntityOperation {
1396 op: PatchEntityOperationType::Unset,
1397 path: child_path,
1398 value: None,
1399 }),
1400 JsonValue::Object(object) if object.is_empty() => {
1401 let child_target = match target {
1402 JsonValue::Object(target_object) => target_object.get(key),
1403 _ => None,
1404 };
1405 if !matches!(child_target, Some(JsonValue::Object(_))) {
1406 operations.push(PatchEntityOperation {
1407 op: PatchEntityOperationType::Set,
1408 path: child_path,
1409 value: Some(JsonValue::Object(Default::default())),
1410 });
1411 }
1412 }
1413 JsonValue::Object(_) => {
1414 let child_target = match target {
1415 JsonValue::Object(target_object) => target_object.get(key),
1416 _ => None,
1417 }
1418 .unwrap_or(&JsonValue::Null);
1419 collect_document_json_merge_patch_operations(
1420 child_target,
1421 child_path,
1422 value,
1423 operations,
1424 );
1425 }
1426 _ => operations.push(PatchEntityOperation {
1427 op: PatchEntityOperationType::Set,
1428 path: child_path,
1429 value: Some(value.clone()),
1430 }),
1431 }
1432 }
1433}
1434
1435impl RedDBRuntime {
1436 pub(crate) fn apply_loaded_patch_entity_core(
1437 &self,
1438 collection: String,
1439 mut entity: crate::storage::UnifiedEntity,
1440 payload: JsonValue,
1441 operations: Vec<PatchEntityOperation>,
1442 ) -> RedDBResult<AppliedEntityMutation> {
1443 let id = entity.id;
1444 let previous_xmax = entity.xmax;
1445 let operations = normalize_ttl_patch_operations(operations)?;
1446 let pre_mutation_fields = entity_row_fields_snapshot(&entity);
1449
1450 let patch_versions = matches!(
1462 entity.data,
1463 crate::storage::EntityData::Row(_)
1464 | crate::storage::EntityData::Node(_)
1465 | crate::storage::EntityData::Edge(_)
1466 ) && self.vcs_is_versioned(&collection).unwrap_or(false);
1467 let versioned_update_xid = if patch_versions {
1468 match self.current_xid() {
1469 Some(xid) => Some(xid),
1470 None => {
1471 let snapshot_manager = self.snapshot_manager();
1472 let xid = snapshot_manager.begin();
1473 snapshot_manager.commit(xid);
1474 Some(xid)
1475 }
1476 }
1477 } else {
1478 None
1479 };
1480 let mut replaced_entity = versioned_update_xid.map(|xid| {
1481 let mut old = entity.clone();
1482 old.set_xmax(xid);
1483 old
1484 });
1485
1486 let db = self.db();
1487 let store = db.store();
1488 let Some(manager) = store.get_collection(&collection) else {
1489 return Err(crate::RedDBError::NotFound(format!(
1490 "collection not found: {collection}"
1491 )));
1492 };
1493
1494 let mut patch_metadata: Option<crate::storage::unified::Metadata> = None;
1495 let mut metadata_changed = false;
1496 let mut modified_columns: Vec<String> = Vec::new();
1497 let mut context_index_dirty = false;
1498 let mut graph_node_type: Option<String> = None;
1499 let mut graph_edge_weight: Option<f32> = None;
1500
1501 let row_contract_timestamps = db
1502 .collection_contract(&collection)
1503 .map(|c| c.timestamps_enabled)
1504 .unwrap_or(false);
1505
1506 match &mut entity.data {
1507 crate::storage::EntityData::Row(row) => {
1508 let is_document_collection = db
1509 .collection_contract(&collection)
1510 .map(|contract| {
1511 contract.declared_model == crate::catalog::CollectionModel::Document
1512 })
1513 .unwrap_or(false);
1514 let binary_body = self.binary_document_body_enabled();
1515 let mut field_ops = Vec::new();
1516 let mut metadata_ops = Vec::new();
1517 let mut document_body_ops = Vec::new();
1518 let mut document_body_replace: Option<JsonValue> = None;
1519 let has_patch_operations = !operations.is_empty();
1520
1521 for mut op in operations {
1522 let Some(root) = op.path.first().map(String::as_str) else {
1523 return Err(crate::RedDBError::Query(
1524 "patch path cannot be empty".to_string(),
1525 ));
1526 };
1527
1528 match root {
1529 "body" if is_document_collection => {
1530 if op.path.len() == 1 {
1531 match op.op {
1532 PatchEntityOperationType::Set
1533 | PatchEntityOperationType::Replace => {
1534 let Some(value) = op.value.take() else {
1535 return Err(crate::RedDBError::Query(
1536 "document body replacement requires a value"
1537 .to_string(),
1538 ));
1539 };
1540 document_body_replace = Some(value);
1541 }
1542 PatchEntityOperationType::Unset => {
1543 return Err(crate::RedDBError::Query(
1544 "document body cannot be unset; replace it instead"
1545 .to_string(),
1546 ));
1547 }
1548 }
1549 continue;
1550 }
1551 if op.path.len() < 2 {
1552 return Err(crate::RedDBError::Query(
1553 "document body patch paths require a nested key; use payload.body for full replacement"
1554 .to_string(),
1555 ));
1556 }
1557 op.path.remove(0);
1558 reject_document_array_position_path(&op.path)?;
1559 document_body_ops.push(op);
1560 }
1561 "fields" | "named" => {
1562 if op.path.len() < 2 {
1563 return Err(crate::RedDBError::Query(
1564 "patch path 'fields' requires a nested key".to_string(),
1565 ));
1566 }
1567 if row_contract_timestamps {
1568 let leaf = op.path.get(1).map(String::as_str);
1569 if matches!(leaf, Some("created_at") | Some("updated_at")) {
1570 return Err(crate::RedDBError::Query(format!(
1571 "collection '{}' manages '{}' automatically — do not set it in UPDATE",
1572 collection,
1573 leaf.unwrap_or("")
1574 )));
1575 }
1576 }
1577 op.path.remove(0);
1578 field_ops.push(op);
1579 }
1580 "metadata" => {
1581 if op.path.len() < 2 {
1582 return Err(crate::RedDBError::Query(
1583 "patch path 'metadata' requires a nested key".to_string(),
1584 ));
1585 }
1586 op.path.remove(0);
1587 metadata_ops.push(op);
1588 }
1589 _ => {
1590 return Err(crate::RedDBError::Query(format!(
1591 "unsupported patch target '{root}' for table rows. Use fields/*, metadata/*, or weight"
1592 )));
1593 }
1594 }
1595 }
1596
1597 if document_body_replace.is_some() || !document_body_ops.is_empty() {
1598 context_index_dirty = true;
1599 let mut body = match document_body_replace {
1600 Some(body) => body,
1601 None => document_body_from_named(
1602 row.named.get_or_insert_with(Default::default),
1603 )?,
1604 };
1605 apply_patch_operations_to_json(&mut body, &document_body_ops)
1606 .map_err(crate::RedDBError::Query)?;
1607 replace_document_row_body(row, body, binary_body, &mut modified_columns)?;
1608 }
1609
1610 if is_document_collection && !has_patch_operations {
1611 let mut body =
1612 document_body_from_named(row.named.get_or_insert_with(Default::default))?;
1613 let previous_body = body.clone();
1614 apply_document_json_merge_patch(
1615 &mut body,
1616 document_merge_patch_payload(&payload),
1617 )?;
1618 if body != previous_body {
1619 context_index_dirty = true;
1620 replace_document_row_body(row, body, binary_body, &mut modified_columns)?;
1621 }
1622 }
1623
1624 if !field_ops.is_empty() {
1625 context_index_dirty = true;
1626 let named = row.named.get_or_insert_with(Default::default);
1627 if is_document_collection {
1628 let mut body = document_body_from_named(named)?;
1632 apply_patch_operations_to_json(&mut body, &field_ops)
1633 .map_err(crate::RedDBError::Query)?;
1634 replace_document_row_body(row, body, binary_body, &mut modified_columns)?;
1635 } else {
1636 for op in &field_ops {
1637 if let Some(col) = op.path.first() {
1638 modified_columns.push(col.clone());
1639 }
1640 }
1641 apply_patch_operations_to_storage_map(named, &field_ops)?;
1642 }
1643 }
1644
1645 if let Some(fields) = payload
1646 .get("fields")
1647 .and_then(crate::json::Value::as_object)
1648 {
1649 if row_contract_timestamps {
1650 for key in fields.keys() {
1651 if key == "created_at" || key == "updated_at" {
1652 return Err(crate::RedDBError::Query(format!(
1653 "collection '{}' manages '{}' automatically — do not set it in UPDATE",
1654 collection, key
1655 )));
1656 }
1657 }
1658 }
1659 context_index_dirty = true;
1660 let named = row.named.get_or_insert_with(Default::default);
1661 if is_document_collection {
1662 let mut body = document_body_from_named(named)?;
1665 if let JsonValue::Object(map) = &mut body {
1666 for (key, value) in fields {
1667 map.insert(key.clone(), value.clone());
1668 }
1669 }
1670 replace_document_row_body(row, body, binary_body, &mut modified_columns)?;
1671 } else {
1672 for (key, value) in fields {
1673 modified_columns.push(key.clone());
1674 named.insert(key.clone(), json_to_storage_value(value)?);
1675 }
1676 }
1677 }
1678
1679 if !metadata_ops.is_empty() {
1680 ensure_non_tree_reserved_metadata_patch_paths(&metadata_ops)?;
1681 let metadata = patch_metadata.get_or_insert_with(|| {
1682 store.get_metadata(&collection, id).unwrap_or_default()
1683 });
1684 let mut metadata_json = metadata_to_json(metadata);
1685 apply_patch_operations_to_json(&mut metadata_json, &metadata_ops)
1686 .map_err(crate::RedDBError::Query)?;
1687 *metadata = metadata_from_json(&metadata_json)?;
1688 metadata_changed = true;
1689 }
1690
1691 if !modified_columns.is_empty() || row_contract_timestamps {
1692 let contract = CollectionContractWriteEnforcer::new(&db, &collection);
1693 let current_fields = if let Some(named) = row.named.take() {
1694 named.into_iter().collect::<Vec<_>>()
1695 } else if let Some(schema) = row.schema.as_ref() {
1696 schema
1697 .iter()
1698 .cloned()
1699 .zip(row.columns.iter().cloned())
1700 .collect::<Vec<_>>()
1701 } else {
1702 Vec::new()
1703 };
1704 let normalized_fields = contract.normalize_update_fields(current_fields)?;
1705 if row_contract_timestamps {
1706 modified_columns.push("updated_at".to_string());
1707 context_index_dirty = true;
1708 }
1709 if contract.requires_uniqueness_check(&modified_columns) {
1710 contract.enforce_row_uniqueness(&normalized_fields, Some(id))?;
1711 }
1712 row.named = Some(normalized_fields.into_iter().collect());
1713 }
1714 }
1715 crate::storage::EntityData::Node(node) => {
1716 let mut field_ops = Vec::new();
1717 let mut metadata_ops = Vec::new();
1718 let mut node_type_ops = Vec::new();
1719
1720 for mut op in operations {
1721 let Some(root) = op.path.first().map(String::as_str) else {
1722 return Err(crate::RedDBError::Query(
1723 "patch path cannot be empty".to_string(),
1724 ));
1725 };
1726
1727 match root {
1728 "fields" | "properties" => {
1729 if op.path.len() < 2 {
1730 return Err(crate::RedDBError::Query(
1731 "patch path 'fields' requires a nested key".to_string(),
1732 ));
1733 }
1734 op.path.remove(0);
1735 field_ops.push(op);
1736 }
1737 "metadata" => {
1738 if op.path.len() < 2 {
1739 return Err(crate::RedDBError::Query(
1740 "patch path 'metadata' requires a nested key".to_string(),
1741 ));
1742 }
1743 op.path.remove(0);
1744 metadata_ops.push(op);
1745 }
1746 "node_type" => {
1747 if op.path.len() != 1 {
1748 return Err(crate::RedDBError::Query(
1749 "patch path 'node_type' does not allow nested keys".to_string(),
1750 ));
1751 }
1752 op.path.clear();
1753 node_type_ops.push(op);
1754 }
1755 _ => {
1756 return Err(crate::RedDBError::Query(format!(
1757 "unsupported patch target '{root}' for graph nodes. Use fields/*, properties/*, node_type, or metadata/*"
1758 )));
1759 }
1760 }
1761 }
1762
1763 for op in node_type_ops {
1764 context_index_dirty = true;
1765 let value = op.value.ok_or_else(|| {
1766 crate::RedDBError::Query("node_type operations require a value".to_string())
1767 })?;
1768
1769 match op.op {
1770 PatchEntityOperationType::Unset => {
1771 return Err(crate::RedDBError::Query(
1772 "node_type cannot be unset through patch operations".to_string(),
1773 ));
1774 }
1775 PatchEntityOperationType::Set | PatchEntityOperationType::Replace => {
1776 let Some(node_type) = value.as_str() else {
1777 return Err(crate::RedDBError::Query(
1778 "node_type operation requires a text value".to_string(),
1779 ));
1780 };
1781 graph_node_type = Some(node_type.to_string());
1782 modified_columns.push("node_type".to_string());
1783 }
1784 }
1785 }
1786
1787 if !field_ops.is_empty() {
1788 context_index_dirty = true;
1789 apply_patch_operations_to_storage_map(&mut node.properties, &field_ops)?;
1790 }
1791
1792 if let Some(fields) = payload
1793 .get("fields")
1794 .and_then(crate::json::Value::as_object)
1795 {
1796 context_index_dirty = true;
1797 for (key, value) in fields {
1798 node.properties
1799 .insert(key.clone(), json_to_storage_value(value)?);
1800 }
1801 }
1802
1803 if !metadata_ops.is_empty() {
1804 ensure_non_tree_reserved_metadata_patch_paths(&metadata_ops)?;
1805 let metadata = patch_metadata.get_or_insert_with(|| {
1806 store.get_metadata(&collection, id).unwrap_or_default()
1807 });
1808 let mut metadata_json = metadata_to_json(metadata);
1809 apply_patch_operations_to_json(&mut metadata_json, &metadata_ops)
1810 .map_err(crate::RedDBError::Query)?;
1811 *metadata = metadata_from_json(&metadata_json)?;
1812 metadata_changed = true;
1813 }
1814 }
1815 crate::storage::EntityData::Edge(edge) => {
1816 let mut field_ops = Vec::new();
1817 let mut metadata_ops = Vec::new();
1818 let mut weight_ops = Vec::new();
1819
1820 for mut op in operations {
1821 let Some(root) = op.path.first().map(String::as_str) else {
1822 return Err(crate::RedDBError::Query(
1823 "patch path cannot be empty".to_string(),
1824 ));
1825 };
1826
1827 match root {
1828 "fields" | "properties" => {
1829 if op.path.len() < 2 {
1830 return Err(crate::RedDBError::Query(
1831 "patch path 'fields' requires a nested key".to_string(),
1832 ));
1833 }
1834 op.path.remove(0);
1835 field_ops.push(op);
1836 }
1837 "weight" => {
1838 if op.path.len() != 1 {
1839 return Err(crate::RedDBError::Query(
1840 "patch path 'weight' does not allow nested keys".to_string(),
1841 ));
1842 }
1843 op.path.clear();
1844 weight_ops.push(op);
1845 }
1846 "metadata" => {
1847 if op.path.len() < 2 {
1848 return Err(crate::RedDBError::Query(
1849 "patch path 'metadata' requires a nested key".to_string(),
1850 ));
1851 }
1852 op.path.remove(0);
1853 metadata_ops.push(op);
1854 }
1855 _ => {
1856 return Err(crate::RedDBError::Query(format!(
1857 "unsupported patch target '{root}' for graph edges. Use fields/*, weight, metadata/*"
1858 )));
1859 }
1860 }
1861 }
1862
1863 if !field_ops.is_empty() {
1864 context_index_dirty = true;
1865 apply_patch_operations_to_storage_map(&mut edge.properties, &field_ops)?;
1866 }
1867
1868 for op in weight_ops {
1869 context_index_dirty = true;
1870 let value = op.value.ok_or_else(|| {
1871 crate::RedDBError::Query("weight operations require a value".to_string())
1872 })?;
1873
1874 match op.op {
1875 PatchEntityOperationType::Unset => {
1876 return Err(crate::RedDBError::Query(
1877 "weight cannot be unset through patch operations".to_string(),
1878 ));
1879 }
1880 PatchEntityOperationType::Set | PatchEntityOperationType::Replace => {
1881 let Some(weight) = value.as_f64() else {
1882 return Err(crate::RedDBError::Query(
1883 "weight operation requires a numeric value".to_string(),
1884 ));
1885 };
1886 graph_edge_weight = Some(weight as f32);
1887 edge.weight = weight as f32;
1888 modified_columns.push("weight".to_string());
1889 }
1890 }
1891 }
1892
1893 if let Some(fields) = payload
1894 .get("fields")
1895 .and_then(crate::json::Value::as_object)
1896 {
1897 context_index_dirty = true;
1898 for (key, value) in fields {
1899 edge.properties
1900 .insert(key.clone(), json_to_storage_value(value)?);
1901 }
1902 }
1903
1904 if !metadata_ops.is_empty() {
1905 ensure_non_tree_reserved_metadata_patch_paths(&metadata_ops)?;
1906 let metadata = patch_metadata.get_or_insert_with(|| {
1907 store.get_metadata(&collection, id).unwrap_or_default()
1908 });
1909 let mut metadata_json = metadata_to_json(metadata);
1910 apply_patch_operations_to_json(&mut metadata_json, &metadata_ops)
1911 .map_err(crate::RedDBError::Query)?;
1912 *metadata = metadata_from_json(&metadata_json)?;
1913 metadata_changed = true;
1914 }
1915 }
1916 crate::storage::EntityData::Vector(vector) => {
1917 let mut field_ops = Vec::new();
1918 let mut metadata_ops = Vec::new();
1919
1920 for mut op in operations {
1921 let Some(root) = op.path.first().map(String::as_str) else {
1922 return Err(crate::RedDBError::Query(
1923 "patch path cannot be empty".to_string(),
1924 ));
1925 };
1926
1927 match root {
1928 "fields" => {
1929 if op.path.len() < 2 {
1930 return Err(crate::RedDBError::Query(
1931 "patch path 'fields' requires a nested key".to_string(),
1932 ));
1933 }
1934 op.path.remove(0);
1935 let Some(target) = op.path.first().map(String::as_str) else {
1936 return Err(crate::RedDBError::Query(
1937 "patch path requires a target under fields".to_string(),
1938 ));
1939 };
1940 if !matches!(target, "dense" | "content" | "sparse") {
1941 return Err(crate::RedDBError::Query(format!(
1942 "unsupported vector patch target '{target}'"
1943 )));
1944 }
1945 field_ops.push(op);
1946 }
1947 "metadata" => {
1948 if op.path.len() < 2 {
1949 return Err(crate::RedDBError::Query(
1950 "patch path 'metadata' requires a nested key".to_string(),
1951 ));
1952 }
1953 op.path.remove(0);
1954 metadata_ops.push(op);
1955 }
1956 _ => {
1957 return Err(crate::RedDBError::Query(format!(
1958 "unsupported patch target '{root}' for vectors. Use fields/* or metadata/*"
1959 )));
1960 }
1961 }
1962 }
1963
1964 if !field_ops.is_empty() {
1965 context_index_dirty = true;
1966 apply_patch_operations_to_vector_fields(vector, &field_ops)?;
1967 }
1968
1969 if let Some(fields) = payload
1970 .get("fields")
1971 .and_then(crate::json::Value::as_object)
1972 {
1973 context_index_dirty = true;
1974 if let Some(content) =
1975 fields.get("content").and_then(crate::json::Value::as_str)
1976 {
1977 vector.content = Some(content.to_string());
1978 }
1979 if let Some(dense) = fields.get("dense") {
1980 vector.dense = dense
1981 .as_array()
1982 .ok_or_else(|| {
1983 crate::RedDBError::Query(
1984 "field 'dense' must be an array".to_string(),
1985 )
1986 })?
1987 .iter()
1988 .map(|value| {
1989 value.as_f64().map(|value| value as f32).ok_or_else(|| {
1990 crate::RedDBError::Query(
1991 "field 'dense' must contain only numbers".to_string(),
1992 )
1993 })
1994 })
1995 .collect::<Result<Vec<_>, _>>()?;
1996 }
1997 }
1998
1999 if !metadata_ops.is_empty() {
2000 ensure_non_tree_reserved_metadata_patch_paths(&metadata_ops)?;
2001 let metadata = patch_metadata.get_or_insert_with(|| {
2002 store.get_metadata(&collection, id).unwrap_or_default()
2003 });
2004 let mut metadata_json = metadata_to_json(metadata);
2005 apply_patch_operations_to_json(&mut metadata_json, &metadata_ops)
2006 .map_err(crate::RedDBError::Query)?;
2007 *metadata = metadata_from_json(&metadata_json)?;
2008 metadata_changed = true;
2009 }
2010 }
2011 crate::storage::EntityData::TimeSeries(_)
2012 | crate::storage::EntityData::QueueMessage(_) => {
2013 return Err(crate::RedDBError::Query(
2014 "patch operations are not supported for TimeSeries or QueueMessage entities"
2015 .to_string(),
2016 ));
2017 }
2018 }
2019
2020 if let Some(node_type) = graph_node_type {
2021 if let crate::storage::EntityKind::GraphNode(node) = &mut entity.kind {
2022 node.node_type = node_type;
2023 }
2024 }
2025 if let Some(weight) = graph_edge_weight {
2026 if let crate::storage::EntityKind::GraphEdge(edge) = &mut entity.kind {
2027 edge.weight = (weight * 1000.0) as u32;
2028 }
2029 }
2030
2031 if let Some(metadata) = payload
2032 .get("metadata")
2033 .and_then(crate::json::Value::as_object)
2034 {
2035 let patch_metadata = patch_metadata
2036 .get_or_insert_with(|| store.get_metadata(&collection, id).unwrap_or_default());
2037 for (key, value) in metadata {
2038 ensure_non_tree_reserved_metadata_key(key)?;
2039 patch_metadata.set(key.clone(), json_to_metadata_value(value)?);
2040 }
2041 metadata_changed = true;
2042 }
2043
2044 for (key, value) in parse_top_level_ttl_metadata_entries(&payload)? {
2045 let patch_metadata = patch_metadata
2046 .get_or_insert_with(|| store.get_metadata(&collection, id).unwrap_or_default());
2047 if matches!(value, crate::storage::unified::MetadataValue::Null) {
2048 patch_metadata.remove(&key);
2049 } else {
2050 patch_metadata.set(key, value);
2051 }
2052 metadata_changed = true;
2053 }
2054
2055 entity.updated_at = std::time::SystemTime::now()
2056 .duration_since(std::time::UNIX_EPOCH)
2057 .unwrap_or_default()
2058 .as_secs();
2059
2060 if let Some(xid) = versioned_update_xid {
2066 let logical_id = entity.logical_id();
2067 entity.id = store.next_entity_id();
2068 entity.set_logical_id(logical_id);
2069 entity.set_xmin(xid);
2070 entity.set_xmax(0);
2071 if let Some(old) = replaced_entity.as_mut() {
2072 old.set_xmax(xid);
2073 }
2074 }
2075
2076 modified_columns = dedupe_modified_columns(modified_columns);
2077
2078 Ok(AppliedEntityMutation {
2079 id: entity.id,
2080 collection,
2081 entity,
2082 metadata: patch_metadata,
2083 modified_columns,
2084 persist_metadata: metadata_changed,
2085 context_index_dirty,
2086 replaced_entity,
2087 replaced_entity_previous_xmax: previous_xmax,
2088 pre_mutation_fields,
2089 })
2090 }
2091
2092 pub(crate) fn apply_loaded_sql_update_row_core(
2093 &self,
2094 collection: String,
2095 mut entity: crate::storage::UnifiedEntity,
2096 static_field_assignments: &[(String, Value)],
2097 dynamic_field_assignments: Vec<(String, Value)>,
2098 static_metadata_assignments: &[(String, MetadataValue)],
2099 dynamic_metadata_assignments: Vec<(String, MetadataValue)>,
2100 row_contract_plan: Option<&RowUpdateContractPlan>,
2101 row_modified_columns_template: &[String],
2102 row_touches_unique_columns: bool,
2103 ) -> RedDBResult<AppliedEntityMutation> {
2104 let id = entity.id;
2105 let previous_xmax = entity.xmax;
2106 let db = self.db();
2107 let store = db.store();
2108 let Some(_) = store.get_collection(&collection) else {
2109 return Err(crate::RedDBError::NotFound(format!(
2110 "collection not found: {collection}"
2111 )));
2112 };
2113
2114 let versioned_update_xid = match self.current_xid() {
2115 Some(xid) => Some(xid),
2116 None => {
2117 let snapshot_manager = self.snapshot_manager();
2118 let xid = snapshot_manager.begin();
2119 snapshot_manager.commit(xid);
2120 Some(xid)
2121 }
2122 };
2123 let mut replaced_entity = versioned_update_xid.map(|xid| {
2124 let mut old = entity.clone();
2125 old.set_xmax(xid);
2126 old
2127 });
2128
2129 let mut patch_metadata: Option<crate::storage::unified::Metadata> = None;
2130 let row_contract_timestamps = row_contract_plan
2131 .map(|plan| plan.timestamps_enabled)
2132 .unwrap_or(false);
2133 let mut metadata_changed = false;
2134 let mut modified_columns = row_modified_columns_template.to_vec();
2135 let mut context_index_dirty = !modified_columns.is_empty();
2136
2137 let pre_mutation_fields = entity_row_fields_snapshot(&entity);
2141
2142 let crate::storage::EntityData::Row(row) = &mut entity.data else {
2143 return Err(crate::RedDBError::Query(
2144 "SQL row update fast path requires a row entity".to_string(),
2145 ));
2146 };
2147
2148 let _ = row_contract_plan;
2149
2150 let is_document_collection = db
2156 .collection_contract(&collection)
2157 .map(|contract| contract.declared_model == crate::catalog::CollectionModel::Document)
2158 .unwrap_or(false);
2159 let kv_key = if row.get_field("value").is_some() || row.columns.len() >= 2 {
2160 row.get_field("key")
2161 .cloned()
2162 .or_else(|| row.columns.first().cloned())
2163 } else {
2164 None
2165 };
2166 if is_document_collection {
2167 let body_assignment = static_field_assignments
2171 .iter()
2172 .chain(dynamic_field_assignments.iter())
2173 .rev()
2174 .find(|(column, _)| column == "body")
2175 .cloned();
2176
2177 match body_assignment {
2178 Some((_, value)) => {
2179 let body = document_body_from_assignment(&value)?;
2180 replace_document_row_body(
2181 row,
2182 body,
2183 self.binary_document_body_enabled(),
2184 &mut modified_columns,
2185 )?;
2186 context_index_dirty = true;
2187 }
2188 None => {
2189 let mut static_row_assignments = Vec::new();
2192 let mut dynamic_row_assignments = Vec::new();
2193 let mut document_body_ops = Vec::new();
2194 for (column, value) in static_field_assignments.iter().cloned() {
2195 if column == "body" {
2196 static_row_assignments.push((column, value));
2197 } else {
2198 document_body_ops.push(document_body_set_operation(&column, value));
2199 }
2200 }
2201 for (column, value) in dynamic_field_assignments {
2202 if column == "body" {
2203 dynamic_row_assignments.push((column, value));
2204 } else {
2205 document_body_ops.push(document_body_set_operation(&column, value));
2206 }
2207 }
2208 apply_row_field_assignments_raw(row, static_row_assignments);
2209 apply_row_field_assignments_raw(row, dynamic_row_assignments);
2210 if !document_body_ops.is_empty() {
2211 let mut body = document_body_from_named(
2212 row.named.get_or_insert_with(Default::default),
2213 )?;
2214 apply_patch_operations_to_json(&mut body, &document_body_ops)
2215 .map_err(crate::RedDBError::Query)?;
2216 replace_document_row_body(
2217 row,
2218 body,
2219 self.binary_document_body_enabled(),
2220 &mut modified_columns,
2221 )?;
2222 context_index_dirty = true;
2223 }
2224 }
2225 }
2226 } else {
2227 let mut all_assignments: Vec<(String, Value)> = static_field_assignments.to_vec();
2229 all_assignments.extend(dynamic_field_assignments);
2230 apply_row_field_assignments_raw(row, all_assignments);
2231 if let Some(key) = kv_key {
2232 set_row_field(row, "key", key);
2233 }
2234 }
2235
2236 for (key, value) in static_metadata_assignments
2237 .iter()
2238 .cloned()
2239 .chain(dynamic_metadata_assignments)
2240 {
2241 ensure_non_tree_reserved_metadata_key(&key)?;
2242 patch_metadata
2243 .get_or_insert_with(|| store.get_metadata(&collection, id).unwrap_or_default())
2244 .set(key, value);
2245 metadata_changed = true;
2246 }
2247
2248 if !modified_columns.is_empty() || row_contract_timestamps {
2249 let contract = CollectionContractWriteEnforcer::new(&db, &collection);
2250 if row_contract_timestamps {
2251 context_index_dirty = true;
2252 set_row_field(
2253 row,
2254 "updated_at",
2255 Value::UnsignedInteger(current_unix_ms_u64()),
2256 );
2257 modified_columns.push("updated_at".to_string());
2258 }
2259 if row_touches_unique_columns {
2260 let current_fields = collect_row_fields(row);
2261 contract.enforce_row_uniqueness(¤t_fields, Some(id))?;
2262 }
2263 }
2264
2265 entity.updated_at = std::time::SystemTime::now()
2266 .duration_since(std::time::UNIX_EPOCH)
2267 .unwrap_or_default()
2268 .as_secs();
2269
2270 if let Some(xid) = versioned_update_xid {
2271 let logical_id = entity.logical_id();
2272 entity.id = store.next_entity_id();
2273 entity.set_logical_id(logical_id);
2274 entity.set_xmin(xid);
2275 entity.set_xmax(0);
2276 if let Some(old) = replaced_entity.as_mut() {
2277 old.set_xmax(xid);
2278 }
2279 }
2280
2281 modified_columns = dedupe_modified_columns(modified_columns);
2282
2283 Ok(AppliedEntityMutation {
2284 id: entity.id,
2285 collection,
2286 entity,
2287 metadata: patch_metadata,
2288 modified_columns,
2289 persist_metadata: metadata_changed,
2290 context_index_dirty,
2291 replaced_entity,
2292 replaced_entity_previous_xmax: previous_xmax,
2293 pre_mutation_fields,
2294 })
2295 }
2296
2297 pub(crate) fn persist_applied_entity_mutations(
2298 &self,
2299 applied: &[AppliedEntityMutation],
2300 ) -> RedDBResult<()> {
2301 if applied.is_empty() {
2302 return Ok(());
2303 }
2304
2305 let store = self.db().store();
2306 let collection = &applied[0].collection;
2307 let Some(manager) = store.get_collection(collection) else {
2308 return Err(crate::RedDBError::NotFound(format!(
2309 "collection not found: {collection}"
2310 )));
2311 };
2312
2313 let mut ordinary = Vec::with_capacity(applied.len());
2314 for item in applied {
2315 if let Some(old_version) = item.replaced_entity.as_ref() {
2316 store
2317 .install_versioned_table_row_update(
2318 collection,
2319 old_version.clone(),
2320 item.entity.clone(),
2321 if item.persist_metadata {
2322 item.metadata.as_ref()
2323 } else {
2324 None
2325 },
2326 )
2327 .map_err(|err| crate::RedDBError::Internal(err.to_string()))?;
2328 if self.current_xid().is_some() {
2329 self.record_pending_versioned_update(
2330 crate::runtime::impl_core::current_connection_id(),
2331 collection,
2332 old_version.id,
2333 item.entity.id,
2334 old_version.xmax,
2335 item.replaced_entity_previous_xmax,
2336 );
2337 }
2338 } else {
2339 ordinary.push(item);
2340 }
2341 }
2342 if ordinary.is_empty() {
2343 return Ok(());
2344 }
2345
2346 manager
2347 .update_hot_batch_with_metadata(ordinary.iter().map(|item| {
2348 (
2349 &item.entity,
2350 item.modified_columns.as_slice(),
2351 if item.persist_metadata {
2352 item.metadata.as_ref()
2353 } else {
2354 None
2355 },
2356 )
2357 }))
2358 .map_err(|err| crate::RedDBError::Query(err.to_string()))?;
2359
2360 let indexed_cols = self
2369 .index_store_ref()
2370 .indexed_columns_set(collection.as_str());
2371 let all_hot = !indexed_cols.is_empty()
2372 && ordinary.iter().all(|item| {
2373 !item.persist_metadata
2374 && !item
2375 .modified_columns
2376 .iter()
2377 .any(|c| indexed_cols.contains(c))
2378 })
2379 || indexed_cols.is_empty() && ordinary.iter().all(|item| !item.persist_metadata);
2380
2381 let entity_refs: Vec<&crate::storage::UnifiedEntity> =
2385 ordinary.iter().map(|item| &item.entity).collect();
2386 let persist_fn = if all_hot {
2387 crate::storage::unified::UnifiedStore::persist_entity_refs_to_pager_wal_only
2388 } else {
2389 crate::storage::unified::UnifiedStore::persist_entity_refs_to_pager
2390 };
2391 persist_fn(store.as_ref(), collection, &entity_refs)
2392 .map_err(|err| crate::RedDBError::Internal(err.to_string()))
2393 }
2394
2395 pub(crate) fn flush_applied_entity_mutation(
2396 &self,
2397 applied: &AppliedEntityMutation,
2398 ) -> RedDBResult<()> {
2399 let store = self.db().store();
2400 if applied.context_index_dirty {
2401 store
2402 .context_index()
2403 .index_entity(&applied.collection, &applied.entity);
2404 }
2405 let mut changed_columns: Option<Vec<String>> = None;
2413 if !applied.pre_mutation_fields.is_empty() {
2414 let post = entity_row_fields_snapshot(&applied.entity);
2415 if !post.is_empty() {
2416 let damage = crate::application::entity::row_damage_vector(
2417 &applied.pre_mutation_fields,
2418 &post,
2419 );
2420 if !damage.is_empty() {
2421 changed_columns = Some(
2422 damage
2423 .touched_columns()
2424 .into_iter()
2425 .map(str::to_string)
2426 .collect(),
2427 );
2428 }
2429
2430 let indexed_cols: std::collections::HashSet<String> = self
2442 .index_store_ref()
2443 .indexed_columns_set_with_parents(applied.collection.as_str());
2444 let pre_index_fields = self
2448 .index_store_ref()
2449 .augment_body_derived_index_fields(&applied.pre_mutation_fields, &indexed_cols);
2450 let post_index_fields = self
2451 .index_store_ref()
2452 .augment_body_derived_index_fields(&post, &indexed_cols);
2453 let modified_cols: std::collections::HashSet<String> =
2454 crate::application::entity::row_damage_vector(
2455 &pre_index_fields,
2456 &post_index_fields,
2457 )
2458 .touched_columns()
2459 .into_iter()
2460 .map(str::to_string)
2461 .collect();
2462 if let Some(old_version) = applied.replaced_entity.as_ref() {
2463 let old_index_fields: Vec<(String, Value)> = pre_index_fields
2464 .iter()
2465 .filter(|(col, _)| indexed_cols.contains(col))
2466 .cloned()
2467 .collect();
2468 let new_index_fields: Vec<(String, Value)> = post_index_fields
2469 .iter()
2470 .filter(|(col, _)| indexed_cols.contains(col))
2471 .cloned()
2472 .collect();
2473 if !old_index_fields.is_empty() {
2474 self.index_store_ref()
2475 .index_entity_delete(
2476 &applied.collection,
2477 old_version.id,
2478 &old_index_fields,
2479 )
2480 .map_err(crate::RedDBError::Internal)?;
2481 }
2482 if !new_index_fields.is_empty() {
2483 self.index_store_ref()
2484 .index_entity_insert(
2485 &applied.collection,
2486 applied.entity.id,
2487 &new_index_fields,
2488 )
2489 .map_err(crate::RedDBError::Internal)?;
2490 }
2491 } else {
2492 let decision = crate::storage::engine::hot_update::decide(
2493 &crate::storage::engine::hot_update::HotUpdateInputs {
2494 collection: applied.collection.as_str(),
2495 indexed_columns: &indexed_cols,
2496 modified_columns: &modified_cols,
2497 new_tuple_size: 0,
2501 page_free_space: usize::MAX,
2502 },
2503 );
2504 if !decision.can_hot {
2505 self.index_store_ref()
2506 .index_entity_update(
2507 &applied.collection,
2508 applied.id,
2509 &pre_index_fields,
2510 &post_index_fields,
2511 )
2512 .map_err(crate::RedDBError::Internal)?;
2513 } else {
2514 tracing::debug!(
2518 collection = %reddb_wire::audit_safe_log_field(&applied.collection),
2519 "hot_update fast-path: skipped index_entity_update"
2520 );
2521 }
2522 }
2523 }
2524 }
2525 self.cdc_emit_prebuilt_with_columns(
2526 crate::replication::cdc::ChangeOperation::Update,
2527 &applied.collection,
2528 &applied.entity,
2529 "entity",
2530 applied.metadata.as_ref(),
2531 true,
2532 changed_columns,
2533 );
2534 Ok(())
2535 }
2536
2537 pub(crate) fn apply_loaded_patch_entity(
2538 &self,
2539 collection: String,
2540 entity: crate::storage::UnifiedEntity,
2541 payload: JsonValue,
2542 operations: Vec<PatchEntityOperation>,
2543 ) -> RedDBResult<CreateEntityOutput> {
2544 let applied =
2545 self.apply_loaded_patch_entity_core(collection, entity, payload, operations)?;
2546 self.persist_applied_entity_mutations(std::slice::from_ref(&applied))?;
2547 self.flush_applied_entity_mutation(&applied)?;
2548 Ok(CreateEntityOutput {
2549 id: applied.id,
2550 entity: Some(public_document_entity(applied.entity)),
2551 })
2552 }
2553}
2554
2555fn public_document_entity(
2564 mut entity: crate::storage::UnifiedEntity,
2565) -> crate::storage::UnifiedEntity {
2566 let crate::storage::EntityData::Row(row) = &mut entity.data else {
2567 return entity;
2568 };
2569 let Some(named) = row.named.as_mut() else {
2570 return entity;
2571 };
2572 let Some(Value::Json(bytes)) = named.get("body") else {
2573 return entity;
2574 };
2575 let bytes = bytes.clone();
2576 if let Some(fields) = crate::document_body::body_fields(&bytes) {
2577 for (name, value) in fields {
2578 named.entry(name).or_insert(value);
2579 }
2580 }
2581 if let Some(body_json) = crate::document_body::decode_container_to_json(&bytes) {
2582 if let Ok(json_bytes) = crate::json::to_vec(&body_json) {
2583 named.insert("body".to_string(), Value::Json(json_bytes));
2584 }
2585 }
2586 entity
2587}
2588
2589fn ensure_non_tree_reserved_metadata_patch_paths(
2590 operations: &[PatchEntityOperation],
2591) -> RedDBResult<()> {
2592 for operation in operations {
2593 let Some(key) = operation.path.first().map(String::as_str) else {
2594 continue;
2595 };
2596 ensure_non_tree_reserved_metadata_key(key)?;
2597 }
2598 Ok(())
2599}
2600
2601fn ensure_non_tree_reserved_metadata_key(key: &str) -> RedDBResult<()> {
2602 if key.starts_with(TREE_METADATA_PREFIX) {
2603 return Err(crate::RedDBError::Query(format!(
2604 "metadata key '{}' is reserved for managed trees",
2605 key
2606 )));
2607 }
2608 Ok(())
2609}
2610
2611fn ensure_non_tree_reserved_metadata_entries(
2612 metadata: &[(String, MetadataValue)],
2613) -> RedDBResult<()> {
2614 for (key, _) in metadata {
2615 ensure_non_tree_reserved_metadata_key(key)?;
2616 }
2617 Ok(())
2618}
2619
2620fn ensure_non_tree_structural_edge_label(label: &str) -> RedDBResult<()> {
2621 if label.eq_ignore_ascii_case(TREE_CHILD_EDGE_LABEL) {
2622 return Err(crate::RedDBError::Query(format!(
2623 "edge label '{}' is reserved for managed trees",
2624 TREE_CHILD_EDGE_LABEL
2625 )));
2626 }
2627 Ok(())
2628}
2629
2630impl RedDBRuntime {
2631 pub(crate) fn create_node_unchecked(
2632 &self,
2633 input: CreateNodeInput,
2634 ) -> RedDBResult<CreateEntityOutput> {
2635 let db = self.db();
2636 let contract = CollectionContractWriteEnforcer::new(&db, &input.collection);
2637 contract.ensure_model(crate::catalog::CollectionModel::Graph)?;
2638 let mut metadata = input.metadata;
2639 apply_collection_default_ttl(&db, &input.collection, &mut metadata);
2640 let mut builder = db.node(&input.collection, &input.label);
2641
2642 if let Some(node_type) = input.node_type {
2643 builder = builder.node_type(node_type);
2644 }
2645
2646 for (key, value) in input.properties {
2647 builder = builder.property(key, value);
2648 }
2649
2650 for (key, value) in metadata {
2651 builder = builder.metadata(key, value);
2652 }
2653
2654 for embedding in input.embeddings {
2655 if let Some(model) = embedding.model {
2656 builder = builder.embedding_with_model(embedding.name, embedding.vector, model);
2657 } else {
2658 builder = builder.embedding(embedding.name, embedding.vector);
2659 }
2660 }
2661
2662 for link in input.table_links {
2663 builder = builder.link_to_table(link.key, link.table);
2664 }
2665
2666 for link in input.node_links {
2667 builder = builder.link_to_weighted(link.target, link.edge_label, link.weight);
2668 }
2669
2670 let id = builder.save()?;
2671 self.stamp_xmin_if_in_txn(&input.collection, id);
2674 refresh_context_index(&db, &input.collection, id)?;
2675 self.cdc_emit(
2676 crate::replication::cdc::ChangeOperation::Insert,
2677 &input.collection,
2678 id.raw(),
2679 "graph_node",
2680 );
2681 Ok(CreateEntityOutput {
2682 id,
2683 entity: db.store().get(&input.collection, id),
2684 })
2685 }
2686
2687 pub(crate) fn create_edge_unchecked(
2688 &self,
2689 input: CreateEdgeInput,
2690 ) -> RedDBResult<CreateEntityOutput> {
2691 let db = self.db();
2692 let contract = CollectionContractWriteEnforcer::new(&db, &input.collection);
2693 contract.ensure_model(crate::catalog::CollectionModel::Graph)?;
2694 let mut metadata = input.metadata;
2695 apply_collection_default_ttl(&db, &input.collection, &mut metadata);
2696 let mut builder = db
2697 .edge(&input.collection, &input.label)
2698 .from(input.from)
2699 .to(input.to);
2700
2701 if let Some(weight) = input.weight {
2702 builder = builder.weight(weight);
2703 }
2704
2705 for (key, value) in input.properties {
2706 builder = builder.property(key, value);
2707 }
2708
2709 for (key, value) in metadata {
2710 builder = builder.metadata(key, value);
2711 }
2712
2713 let id = builder.save()?;
2714 self.stamp_xmin_if_in_txn(&input.collection, id);
2717 refresh_context_index(&db, &input.collection, id)?;
2718 self.cdc_emit(
2719 crate::replication::cdc::ChangeOperation::Insert,
2720 &input.collection,
2721 id.raw(),
2722 "graph_edge",
2723 );
2724 Ok(CreateEntityOutput {
2725 id,
2726 entity: db.store().get(&input.collection, id),
2727 })
2728 }
2729}
2730
2731fn create_rows_batch_prevalidated_columnar_with_outputs(
2732 runtime: &RedDBRuntime,
2733 collection: String,
2734 column_names: std::sync::Arc<Vec<String>>,
2735 rows: Vec<Vec<crate::storage::schema::Value>>,
2736) -> RedDBResult<Vec<CreateEntityOutput>> {
2737 use crate::storage::{
2738 unified::{EntityData, EntityKind, RowData},
2739 EntityId, UnifiedEntity,
2740 };
2741 use std::sync::Arc;
2742
2743 if rows.is_empty() {
2744 return Ok(Vec::new());
2745 }
2746 runtime.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
2747 runtime.check_batch_size(rows.len())?;
2748 runtime.check_db_size()?;
2749
2750 let db = runtime.db();
2751 let contract = CollectionContractWriteEnforcer::new(&db, &collection);
2752 contract.ensure_model(crate::catalog::CollectionModel::Table)?;
2753
2754 let store = db.store();
2755 let table_arc: Arc<str> = Arc::from(collection.as_str());
2756
2757 let indexed_cols = runtime
2758 .index_store_ref()
2759 .indexed_columns_set(collection.as_str());
2760 let has_secondary_indexes = !indexed_cols.is_empty();
2761 let mut field_snapshots: Vec<Vec<(String, crate::storage::schema::Value)>> =
2762 if has_secondary_indexes {
2763 Vec::with_capacity(rows.len())
2764 } else {
2765 Vec::new()
2766 };
2767
2768 let entities: Vec<UnifiedEntity> = rows
2769 .into_iter()
2770 .map(|values| {
2771 if has_secondary_indexes {
2772 let mut snap: Vec<(String, crate::storage::schema::Value)> =
2773 Vec::with_capacity(indexed_cols.len());
2774 for (name, val) in column_names.iter().zip(values.iter()) {
2775 if indexed_cols.contains(name) {
2776 snap.push((name.clone(), val.clone()));
2777 }
2778 }
2779 field_snapshots.push(snap);
2780 }
2781 let mut row = RowData::new(values);
2782 row.schema = Some(Arc::clone(&column_names));
2783 UnifiedEntity::new(
2784 EntityId::new(0),
2785 EntityKind::TableRow {
2786 table: Arc::clone(&table_arc),
2787 row_id: 0,
2788 },
2789 EntityData::Row(row),
2790 )
2791 })
2792 .collect();
2793
2794 let ids = store
2795 .bulk_insert(&collection, entities)
2796 .map_err(|e| crate::RedDBError::Internal(format!("{e:?}")))?;
2797
2798 if has_secondary_indexes {
2799 let index_rows: Vec<(EntityId, Vec<(String, crate::storage::schema::Value)>)> = ids
2800 .iter()
2801 .zip(field_snapshots)
2802 .map(|(id, fields)| (*id, fields))
2803 .collect();
2804 runtime
2805 .index_store_ref()
2806 .index_entity_insert_batch(&collection, &index_rows)
2807 .map_err(crate::RedDBError::Internal)?;
2808 }
2809
2810 runtime.invalidate_result_cache();
2811 runtime.cdc_emit_insert_batch_no_cache_invalidate(&collection, &ids, "table");
2812
2813 Ok(ids
2814 .into_iter()
2815 .map(|id| CreateEntityOutput { id, entity: None })
2816 .collect())
2817}
2818
2819impl RuntimeEntityPort for RedDBRuntime {
2820 fn create_row(&self, input: CreateRowInput) -> RedDBResult<CreateEntityOutput> {
2821 self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
2822 let db = self.db();
2823 let CreateRowInput {
2824 collection,
2825 fields,
2826 metadata: input_metadata,
2827 node_links,
2828 vector_links,
2829 } = input;
2830 let contract = CollectionContractWriteEnforcer::new(&db, &collection);
2831 contract.ensure_model(crate::catalog::CollectionModel::Table)?;
2832 let mut metadata = input_metadata;
2833 apply_collection_default_ttl(&db, &collection, &mut metadata);
2834 let fields = contract.normalize_insert_fields(fields)?;
2835 contract.enforce_row_uniqueness(&fields, None)?;
2836 let engine = self.mutation_engine();
2838 let result = engine.apply(
2839 collection.clone(),
2840 vec![crate::runtime::mutation::MutationRow {
2841 fields,
2842 metadata,
2843 node_links,
2844 vector_links,
2845 }],
2846 )?;
2847 let id = result.ids[0];
2848 Ok(CreateEntityOutput {
2853 id,
2854 entity: db.store().get(&collection, id),
2855 })
2856 }
2857
2858 fn create_rows_batch(
2859 &self,
2860 input: CreateRowsBatchInput,
2861 ) -> RedDBResult<Vec<CreateEntityOutput>> {
2862 if input.rows.is_empty() {
2863 return Ok(Vec::new());
2864 }
2865 self.check_batch_size(input.rows.len())?;
2866 self.check_db_size()?;
2867
2868 let db = self.db();
2869 let collection = input.collection;
2870 let contract = CollectionContractWriteEnforcer::new(&db, &collection);
2871 contract.ensure_model(crate::catalog::CollectionModel::Table)?;
2872
2873 let mut prepared_rows = Vec::with_capacity(input.rows.len());
2874 let mut uniqueness_rows = Vec::with_capacity(input.rows.len());
2875 for row in input.rows {
2876 if row.collection != collection {
2877 return Err(crate::RedDBError::Query(format!(
2878 "batch row collection mismatch: expected '{}', got '{}'",
2879 collection, row.collection
2880 )));
2881 }
2882
2883 let mut metadata = row.metadata;
2884 apply_collection_default_ttl(&db, &collection, &mut metadata);
2885 let fields = contract.normalize_insert_fields(row.fields)?;
2886 contract.enforce_row_uniqueness(&fields, None)?;
2887 uniqueness_rows.push(fields.clone());
2888 prepared_rows.push((fields, metadata, row.node_links, row.vector_links));
2889 }
2890
2891 contract.enforce_batch_uniqueness(&uniqueness_rows)?;
2892
2893 let engine = {
2896 let e = self.mutation_engine();
2897 if input.suppress_events {
2898 e.with_suppress_events()
2899 } else {
2900 e
2901 }
2902 };
2903 let mutation_rows: Vec<crate::runtime::mutation::MutationRow> = prepared_rows
2904 .into_iter()
2905 .map(|(fields, metadata, node_links, vector_links)| {
2906 crate::runtime::mutation::MutationRow {
2907 fields,
2908 metadata,
2909 node_links,
2910 vector_links,
2911 }
2912 })
2913 .collect();
2914
2915 let result = engine
2916 .apply(collection.clone(), mutation_rows)
2917 .map_err(|e| crate::RedDBError::Internal(e.to_string()))?;
2918
2919 let store = db.store();
2920 Ok(result
2921 .ids
2922 .into_iter()
2923 .map(|id| CreateEntityOutput {
2924 id,
2925 entity: store.get(&collection, id),
2926 })
2927 .collect())
2928 }
2929
2930 fn create_rows_batch_prevalidated_columnar(
2931 &self,
2932 collection: String,
2933 column_names: std::sync::Arc<Vec<String>>,
2934 rows: Vec<Vec<crate::storage::schema::Value>>,
2935 ) -> RedDBResult<usize> {
2936 create_rows_batch_prevalidated_columnar_with_outputs(self, collection, column_names, rows)
2937 .map(|outputs| outputs.len())
2938 }
2939
2940 fn create_rows_batch_columnar(
2941 &self,
2942 collection: String,
2943 column_names: std::sync::Arc<Vec<String>>,
2944 rows: Vec<Vec<crate::storage::schema::Value>>,
2945 ) -> RedDBResult<usize> {
2946 self.create_rows_batch_columnar_with_outputs(collection, column_names, rows)
2947 .map(|outputs| outputs.len())
2948 }
2949
2950 fn create_rows_batch_columnar_with_outputs(
2951 &self,
2952 collection: String,
2953 column_names: std::sync::Arc<Vec<String>>,
2954 rows: Vec<Vec<crate::storage::schema::Value>>,
2955 ) -> RedDBResult<Vec<CreateEntityOutput>> {
2956 if rows.is_empty() {
2957 return Ok(Vec::new());
2958 }
2959 self.check_batch_size(rows.len())?;
2960 self.check_db_size()?;
2961
2962 let db = self.db();
2963 let contract = CollectionContractWriteEnforcer::new(&db, &collection);
2964 contract.ensure_model(crate::catalog::CollectionModel::Table)?;
2965
2966 let needs_normalisation = match db.collection_contract(&collection) {
2976 Some(c) => {
2977 c.declared_model == crate::catalog::CollectionModel::Table
2978 && (!c.declared_columns.is_empty()
2979 || c.table_def
2980 .as_ref()
2981 .map(|t| !t.columns.is_empty())
2982 .unwrap_or(false))
2983 }
2984 None => false,
2985 };
2986 if !needs_normalisation {
2987 return create_rows_batch_prevalidated_columnar_with_outputs(
2988 self,
2989 collection,
2990 column_names,
2991 rows,
2992 );
2993 }
2994
2995 let ncols = column_names.len();
3002 let tuple_rows: Vec<CreateRowInput> = rows
3003 .into_iter()
3004 .map(|values| {
3005 let mut fields: Vec<(String, crate::storage::schema::Value)> =
3006 Vec::with_capacity(ncols);
3007 for (name, value) in column_names.iter().zip(values) {
3008 fields.push((name.clone(), value));
3009 }
3010 CreateRowInput {
3011 collection: collection.clone(),
3012 fields,
3013 metadata: Vec::new(),
3014 node_links: Vec::new(),
3015 vector_links: Vec::new(),
3016 }
3017 })
3018 .collect();
3019 self.create_rows_batch(CreateRowsBatchInput {
3020 collection,
3021 rows: tuple_rows,
3022 suppress_events: false,
3023 })
3024 }
3025
3026 fn create_rows_batch_prevalidated(&self, input: CreateRowsBatchInput) -> RedDBResult<usize> {
3027 if input.rows.is_empty() {
3028 return Ok(0);
3029 }
3030 self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
3031 self.check_batch_size(input.rows.len())?;
3032 self.check_db_size()?;
3033
3034 let db = self.db();
3035 let collection = input.collection;
3036 let contract = CollectionContractWriteEnforcer::new(&db, &collection);
3041 contract.ensure_model(crate::catalog::CollectionModel::Table)?;
3042
3043 let default_ttl_ms = db.collection_default_ttl_ms(&collection);
3049
3050 let mutation_rows: Vec<crate::runtime::mutation::MutationRow> =
3051 Vec::with_capacity(input.rows.len());
3052 let mut mutation_rows = mutation_rows;
3053 for row in input.rows {
3054 if row.collection != collection {
3055 return Err(crate::RedDBError::Query(format!(
3056 "batch row collection mismatch: expected '{}', got '{}'",
3057 collection, row.collection
3058 )));
3059 }
3060 let mut metadata = row.metadata;
3061 if let Some(ttl) = default_ttl_ms {
3062 if !has_internal_ttl_metadata(&metadata) {
3063 metadata.push((
3064 "_ttl_ms".to_string(),
3065 if ttl <= i64::MAX as u64 {
3066 MetadataValue::Int(ttl as i64)
3067 } else {
3068 MetadataValue::Timestamp(ttl)
3069 },
3070 ));
3071 }
3072 }
3073 mutation_rows.push(crate::runtime::mutation::MutationRow {
3074 fields: row.fields,
3075 metadata,
3076 node_links: row.node_links,
3077 vector_links: row.vector_links,
3078 });
3079 }
3080
3081 let engine = self.mutation_engine();
3082 let result = engine
3083 .apply(collection, mutation_rows)
3084 .map_err(|e| crate::RedDBError::Internal(e.to_string()))?;
3085 Ok(result.ids.len())
3086 }
3087
3088 fn create_node(&self, input: CreateNodeInput) -> RedDBResult<CreateEntityOutput> {
3089 self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
3090 crate::reserved_fields::ensure_no_reserved_public_item_fields(
3091 input.properties.iter().map(|(key, _)| key.as_str()),
3092 &format!("node '{}'", input.collection),
3093 )?;
3094 ensure_non_tree_reserved_metadata_entries(&input.metadata)?;
3095 self.create_node_unchecked(input)
3096 }
3097
3098 fn create_edge(&self, input: CreateEdgeInput) -> RedDBResult<CreateEntityOutput> {
3099 self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
3100 crate::reserved_fields::ensure_no_reserved_public_item_fields(
3101 input.properties.iter().map(|(key, _)| key.as_str()),
3102 &format!("edge '{}'", input.collection),
3103 )?;
3104 ensure_non_tree_structural_edge_label(&input.label)?;
3105 ensure_non_tree_reserved_metadata_entries(&input.metadata)?;
3106 self.create_edge_unchecked(input)
3107 }
3108
3109 fn create_vector(&self, input: CreateVectorInput) -> RedDBResult<CreateEntityOutput> {
3110 self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
3111 let db = self.db();
3112 let contract = CollectionContractWriteEnforcer::new(&db, &input.collection);
3113 contract.ensure_model(crate::catalog::CollectionModel::Vector)?;
3114 ensure_vector_dimension_contract(&db, &input.collection, input.dense.len())?;
3115 let mut metadata = input.metadata;
3116 apply_collection_default_ttl(&db, &input.collection, &mut metadata);
3117 let mut builder = db.vector(&input.collection).dense(input.dense);
3118
3119 if let Some(content) = input.content {
3120 builder = builder.content(content);
3121 }
3122
3123 for (key, value) in metadata {
3124 builder = builder.metadata(key, value);
3125 }
3126
3127 if let Some(link_row) = input.link_row {
3128 builder = builder.link_to_table(link_row);
3129 }
3130
3131 if let Some(link_node) = input.link_node {
3132 builder = builder.link_to_node(link_node);
3133 }
3134
3135 let id = builder.save()?;
3136 let dense_for_turbo = match db.store().get(&input.collection, id).map(|e| e.data) {
3137 Some(crate::storage::unified::EntityData::Vector(data)) => Some(data.dense.clone()),
3138 _ => None,
3139 };
3140 self.stamp_xmin_if_in_txn(&input.collection, id);
3143 refresh_context_index(&db, &input.collection, id)?;
3144 if let (Some(state), Some(dense)) = (db.turbo_state(&input.collection), dense_for_turbo) {
3150 state.ensure_populated(&db.store(), &input.collection);
3154 use crate::runtime::turbo_crash_inject::{fire, InjectionPoint};
3156 fire(InjectionPoint::BeforeWalFsync);
3157 let _ = db
3158 .store()
3159 .append_vector_insert_record(&input.collection, id.raw(), &dense);
3160 fire(InjectionPoint::BeforeIndexCommit);
3161 let mut index = state.index.lock();
3162 index.insert(id, dense.clone());
3163 fire(InjectionPoint::BeforeExtentFsync);
3170 if let Some(extent) = state.extent.lock().as_mut() {
3171 let packed = index.encode_for_extent(&dense);
3172 let _ = extent.append(&packed);
3173 }
3174 }
3175 self.cdc_emit(
3176 crate::replication::cdc::ChangeOperation::Insert,
3177 &input.collection,
3178 id.raw(),
3179 "vector",
3180 );
3181 Ok(CreateEntityOutput {
3182 id,
3183 entity: db.store().get(&input.collection, id),
3184 })
3185 }
3186
3187 fn create_document(&self, input: CreateDocumentInput) -> RedDBResult<CreateEntityOutput> {
3188 self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
3189 let db = self.db();
3190 let contract = CollectionContractWriteEnforcer::new(&db, &input.collection);
3191 contract.ensure_model(crate::catalog::CollectionModel::Document)?;
3192
3193 if let JsonValue::Object(ref map) = input.body {
3194 crate::reserved_fields::ensure_no_reserved_public_item_fields(
3195 map.keys().map(String::as_str),
3196 &format!("document '{}'", input.collection),
3197 )?;
3198 }
3199
3200 let binary_body = self.binary_document_body_enabled();
3204 let body_bytes = crate::document_body::serialize_document_body(&input.body, binary_body)?;
3205 let fields: Vec<(String, crate::storage::schema::Value)> = vec![(
3206 "body".to_string(),
3207 crate::storage::schema::Value::Json(body_bytes),
3208 )];
3209
3210 let mut metadata = input.metadata;
3211 apply_collection_default_ttl(&db, &input.collection, &mut metadata);
3212 let columns: Vec<(&str, crate::storage::schema::Value)> = fields
3213 .iter()
3214 .map(|(key, value)| (key.as_str(), value.clone()))
3215 .collect();
3216 let mut builder = db.row(&input.collection, columns);
3217
3218 for (key, value) in metadata {
3219 builder = builder.metadata(key, value);
3220 }
3221
3222 for node in input.node_links {
3223 builder = builder.link_to_node(node);
3224 }
3225
3226 for vector in input.vector_links {
3227 builder = builder.link_to_vector(vector);
3228 }
3229
3230 let id = builder.save()?;
3231 self.stamp_xmin_if_in_txn(&input.collection, id);
3233 refresh_context_index(&db, &input.collection, id)?;
3234 self.cdc_emit(
3235 crate::replication::cdc::ChangeOperation::Insert,
3236 &input.collection,
3237 id.raw(),
3238 "document",
3239 );
3240 Ok(CreateEntityOutput {
3241 id,
3242 entity: db.store().get(&input.collection, id),
3243 })
3244 }
3245
3246 fn create_kv(&self, input: CreateKvInput) -> RedDBResult<CreateEntityOutput> {
3247 let db = self.db();
3248 let contract = CollectionContractWriteEnforcer::new(&db, &input.collection);
3249 let declared_model = db
3250 .collection_contract(&input.collection)
3251 .map(|contract| contract.declared_model);
3252 let value = if declared_model == Some(crate::catalog::CollectionModel::Vault) {
3253 contract.ensure_model(crate::catalog::CollectionModel::Vault)?;
3254 self.seal_vault_value(&input.collection, input.value)?
3255 } else {
3256 contract.ensure_model(crate::catalog::CollectionModel::Kv)?;
3257 input.value
3258 };
3259 let fields = vec![
3260 (
3261 "key".to_string(),
3262 crate::storage::schema::Value::text(input.key),
3263 ),
3264 ("value".to_string(), value),
3265 ];
3266 let collection = input.collection;
3267 let result = self.mutation_engine().apply(
3268 collection.clone(),
3269 vec![crate::runtime::mutation::MutationRow {
3270 fields,
3271 metadata: input.metadata,
3272 node_links: Vec::new(),
3273 vector_links: Vec::new(),
3274 }],
3275 )?;
3276 let id = result.ids[0];
3277 Ok(CreateEntityOutput {
3278 id,
3279 entity: db.store().get(&collection, id),
3280 })
3281 }
3282
3283 fn create_timeseries_point(
3284 &self,
3285 input: CreateTimeSeriesPointInput,
3286 ) -> RedDBResult<CreateEntityOutput> {
3287 self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
3288 let db = self.db();
3289 let contract = CollectionContractWriteEnforcer::new(&db, &input.collection);
3290 contract.ensure_model(crate::catalog::CollectionModel::TimeSeries)?;
3291
3292 let mut fields = vec![
3293 (
3294 "metric".to_string(),
3295 crate::storage::schema::Value::text(input.metric),
3296 ),
3297 (
3298 "value".to_string(),
3299 crate::storage::schema::Value::Float(input.value),
3300 ),
3301 ];
3302
3303 if let Some(timestamp_ns) = input.timestamp_ns {
3304 fields.push((
3305 "timestamp".to_string(),
3306 crate::storage::schema::Value::UnsignedInteger(timestamp_ns),
3307 ));
3308 }
3309
3310 if !input.tags.is_empty() {
3311 let tags_json = JsonValue::Object(
3312 input
3313 .tags
3314 .into_iter()
3315 .map(|(key, value)| (key, JsonValue::String(value)))
3316 .collect(),
3317 );
3318 let tags_bytes = json_to_vec(&tags_json).map_err(|err| {
3319 crate::RedDBError::Query(format!("failed to serialize timeseries tags: {err}"))
3320 })?;
3321 fields.push((
3322 "tags".to_string(),
3323 crate::storage::schema::Value::Json(tags_bytes),
3324 ));
3325 }
3326
3327 let collection = input.collection;
3328 let id = self.insert_timeseries_point(&collection, fields, input.metadata)?;
3329 self.stamp_xmin_if_in_txn(&collection, id);
3332 refresh_context_index(&db, &collection, id)?;
3333
3334 Ok(CreateEntityOutput {
3335 id,
3336 entity: db.store().get(&collection, id),
3337 })
3338 }
3339
3340 fn get_kv(
3341 &self,
3342 collection: &str,
3343 key: &str,
3344 ) -> RedDBResult<Option<(crate::storage::schema::Value, crate::storage::EntityId)>> {
3345 let db = self.db();
3346 ensure_collection_model_read(&db, collection, crate::catalog::CollectionModel::Kv)?;
3347 let store = db.store();
3348 let Some(manager) = store.get_collection(collection) else {
3349 return Ok(None);
3350 };
3351 let entities = manager.query_all(|_| true);
3352 for entity in entities {
3353 if let crate::storage::EntityData::Row(ref row) = entity.data {
3354 if let Some(ref named) = row.named {
3355 if let Some(crate::storage::schema::Value::Text(ref k)) = named.get("key") {
3356 if &**k == key {
3357 let value = named
3358 .get("value")
3359 .cloned()
3360 .unwrap_or(crate::storage::schema::Value::Null);
3361 return Ok(Some((value, entity.id)));
3362 }
3363 }
3364 }
3365 }
3366 }
3367 Ok(None)
3368 }
3369
3370 fn delete_kv(&self, collection: &str, key: &str) -> RedDBResult<bool> {
3371 self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
3372 let found = self.get_kv(collection, key)?;
3373 if let Some((_, id)) = found {
3374 let db = self.db();
3375 let store = db.store();
3376 let deleted = store
3377 .delete(collection, id)
3378 .map_err(|err| crate::RedDBError::Internal(err.to_string()))?;
3379 if deleted {
3380 store.context_index().remove_entity(id);
3381 }
3382 Ok(deleted)
3383 } else {
3384 Ok(false)
3385 }
3386 }
3387
3388 fn patch_entity(&self, input: PatchEntityInput) -> RedDBResult<CreateEntityOutput> {
3389 self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
3390 let PatchEntityInput {
3391 collection,
3392 id,
3393 payload,
3394 operations,
3395 } = input;
3396 let db = self.db();
3397 let store = db.store();
3398 let Some(manager) = store.get_collection(&collection) else {
3399 return Err(crate::RedDBError::NotFound(format!(
3400 "collection not found: {collection}"
3401 )));
3402 };
3403 let Some(entity) = manager.get(id) else {
3404 return Err(crate::RedDBError::NotFound(format!(
3405 "entity not found: {}",
3406 id.raw()
3407 )));
3408 };
3409 self.apply_loaded_patch_entity(collection, entity, payload, operations)
3410 }
3411
3412 fn delete_entity(&self, input: DeleteEntityInput) -> RedDBResult<DeleteEntityOutput> {
3413 self.check_write(crate::runtime::write_gate::WriteKind::Dml)?;
3414 let store = self.db().store();
3415 let pre_delete_fields = store
3419 .get(&input.collection, input.id)
3420 .as_ref()
3421 .map(entity_row_fields_snapshot)
3422 .unwrap_or_default();
3423 let deleted = store
3427 .delete(&input.collection, input.id)
3428 .map_err(|err| crate::RedDBError::Internal(err.to_string()))?;
3429 if deleted {
3430 store.context_index().remove_entity(input.id);
3431 if !pre_delete_fields.is_empty() {
3434 self.index_store_ref()
3435 .index_entity_delete(&input.collection, input.id, &pre_delete_fields)
3436 .map_err(crate::RedDBError::Internal)?;
3437 }
3438 self.cdc_emit(
3439 crate::replication::cdc::ChangeOperation::Delete,
3440 &input.collection,
3441 input.id.raw(),
3442 "entity",
3443 );
3444 }
3445 Ok(DeleteEntityOutput {
3446 deleted,
3447 id: input.id,
3448 })
3449 }
3450}