Skip to main content

teaql_runtime/
entity_runtime.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::sync::{Arc, Mutex};
3
4use teaql_core::{Record, Value};
5
6#[derive(Debug, Clone)]
7pub struct EntityKey {
8    pub entity: String,
9    pub id: Value,
10    id_key: String,
11}
12
13impl EntityKey {
14    pub fn new(entity: impl Into<String>, id: impl Into<Value>) -> Self {
15        let id = id.into();
16        Self {
17            entity: entity.into(),
18            id_key: value_key(&id),
19            id,
20        }
21    }
22}
23
24impl PartialEq for EntityKey {
25    fn eq(&self, other: &Self) -> bool {
26        self.entity == other.entity && self.id_key == other.id_key
27    }
28}
29
30impl Eq for EntityKey {}
31
32impl PartialOrd for EntityKey {
33    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
34        Some(self.cmp(other))
35    }
36}
37
38impl Ord for EntityKey {
39    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
40        self.entity
41            .cmp(&other.entity)
42            .then_with(|| self.id_key.cmp(&other.id_key))
43    }
44}
45
46fn value_key(value: &Value) -> String {
47    match value {
48        Value::Null => "null".to_owned(),
49        Value::Bool(value) => format!("bool:{value}"),
50        Value::I64(value) => format!("i64:{value}"),
51        Value::U64(value) => format!("u64:{value}"),
52        Value::F64(value) => format!("f64:{value}"),
53        Value::Decimal(value) => format!("decimal:{value}"),
54        Value::Text(value) => format!("text:{value}"),
55        Value::Json(value) => format!("json:{value}"),
56        Value::Date(value) => format!("date:{value}"),
57        Value::Timestamp(value) => format!("timestamp:{}", value.to_rfc3339()),
58        Value::Object(_) => "object".to_owned(),
59        Value::List(_) => "list".to_owned(),
60    }
61}
62
63#[derive(Debug, Clone, Default, PartialEq)]
64pub struct EntityChangeSet {
65    changes: BTreeMap<EntityKey, Record>,
66}
67
68impl EntityChangeSet {
69    pub fn is_empty(&self) -> bool {
70        self.changes.is_empty()
71    }
72
73    pub fn set(&mut self, key: EntityKey, field: impl Into<String>, value: Value) {
74        self.changes
75            .entry(key)
76            .or_default()
77            .insert(field.into(), value);
78    }
79
80    pub fn get(&self, key: &EntityKey, field: &str) -> Option<&Value> {
81        self.changes.get(key).and_then(|changes| changes.get(field))
82    }
83
84    pub fn changes(&self) -> &BTreeMap<EntityKey, Record> {
85        &self.changes
86    }
87
88    /// Remove all pending changes for a specific entity key.
89    pub fn clear_entity(&mut self, key: &EntityKey) {
90        self.changes.remove(key);
91    }
92
93    /// Get the set of field names that have been modified for a given entity key.
94    pub fn field_names(&self, key: &EntityKey) -> BTreeSet<String> {
95        self.changes
96            .get(key)
97            .map(|record| record.keys().cloned().collect())
98            .unwrap_or_default()
99    }
100}
101
102#[derive(Debug, Clone, Default, PartialEq)]
103pub struct ChangeSetStack {
104    stack: Vec<EntityChangeSet>,
105}
106
107impl ChangeSetStack {
108    pub fn current_mut(&mut self) -> &mut EntityChangeSet {
109        if self.stack.is_empty() {
110            self.stack.push(EntityChangeSet::default());
111        }
112        self.stack.last_mut().expect("change set stack has current")
113    }
114
115    pub fn current(&self) -> Option<&EntityChangeSet> {
116        self.stack.last()
117    }
118
119    pub fn push(&mut self) {
120        self.stack.push(EntityChangeSet::default());
121    }
122
123    pub fn pop(&mut self) -> Option<EntityChangeSet> {
124        self.stack.pop()
125    }
126
127    pub fn get(&self, key: &EntityKey, field: &str) -> Option<Value> {
128        self.stack
129            .iter()
130            .rev()
131            .find_map(|change_set| change_set.get(key, field).cloned())
132    }
133
134    pub fn set(&mut self, key: EntityKey, field: impl Into<String>, value: Value) {
135        self.current_mut().set(key, field, value);
136    }
137
138    pub fn clear_current(&mut self) {
139        if let Some(current) = self.stack.last_mut() {
140            *current = EntityChangeSet::default();
141        }
142    }
143
144    /// Remove all pending changes for a specific entity key across all stack levels.
145    pub fn clear_entity(&mut self, key: &EntityKey) {
146        for change_set in &mut self.stack {
147            change_set.clear_entity(key);
148        }
149    }
150
151    /// Get the union of all changed field names for a given entity key across all stack levels.
152    /// This is the Rust equivalent of Java's `entity.getUpdatedProperties()`.
153    pub fn changed_field_names(&self, key: &EntityKey) -> BTreeSet<String> {
154        let mut fields = BTreeSet::new();
155        for change_set in &self.stack {
156            fields.extend(change_set.field_names(key));
157        }
158        fields
159    }
160}
161
162#[derive(Debug, Default)]
163pub struct RootContext {
164    change_sets: ChangeSetStack,
165    /// Annotation comment for observability during graph save.
166    comment: Option<String>,
167    /// Entity keys that have been marked for deletion.
168    /// When the entity is saved, the graph save pipeline will treat these as Remove operations.
169    deleted_keys: BTreeSet<EntityKey>,
170    /// Indicates if this entity is newly created in memory.
171    is_new: bool,
172    /// The original loaded snapshot record, used to avoid redundant fetching during save.
173    original_record: Option<Record>,
174}
175
176#[derive(Debug, Clone, Default)]
177pub struct EntityRoot {
178    inner: Arc<Mutex<RootContext>>,
179}
180
181impl PartialEq for EntityRoot {
182    fn eq(&self, other: &Self) -> bool {
183        Arc::ptr_eq(&self.inner, &other.inner)
184    }
185}
186
187impl EntityRoot {
188    pub fn push_change_set(&self) {
189        self.inner
190            .lock()
191            .unwrap_or_else(|e| e.into_inner())
192            .change_sets
193            .push();
194    }
195
196    pub fn pop_change_set(&self) -> Option<EntityChangeSet> {
197        self.inner
198            .lock()
199            .unwrap_or_else(|e| e.into_inner())
200            .change_sets
201            .pop()
202    }
203
204    pub fn clear_current_change_set(&self) {
205        self.inner
206            .lock()
207            .unwrap_or_else(|e| e.into_inner())
208            .change_sets
209            .clear_current();
210    }
211
212    pub fn set(&self, key: EntityKey, field: impl Into<String>, value: impl Into<Value>) {
213        self.inner
214            .lock()
215            .unwrap_or_else(|e| e.into_inner())
216            .change_sets
217            .set(key, field, value.into());
218    }
219
220    pub fn get(&self, key: &EntityKey, field: &str) -> Option<Value> {
221        self.inner
222            .lock()
223            .unwrap_or_else(|e| e.into_inner())
224            .change_sets
225            .get(key, field)
226    }
227
228    pub fn current_change_set(&self) -> EntityChangeSet {
229        self.inner
230            .lock()
231            .unwrap_or_else(|e| e.into_inner())
232            .change_sets
233            .current()
234            .cloned()
235            .unwrap_or_default()
236    }
237
238    /// Set an annotation comment on this entity root.
239    /// The comment propagates through the graph save process for observability.
240    pub fn set_comment(&self, comment: impl Into<String>) {
241        self.inner
242            .lock()
243            .unwrap_or_else(|e| e.into_inner())
244            .comment = Some(comment.into());
245    }
246
247    /// Get the annotation comment, if any.
248    pub fn get_comment(&self) -> Option<String> {
249        self.inner
250            .lock()
251            .unwrap_or_else(|e| e.into_inner())
252            .comment
253            .clone()
254    }
255
256    /// Mark this entity root as a newly created entity in memory.
257    pub fn mark_as_new(&self) {
258        self.inner
259            .lock()
260            .unwrap_or_else(|e| e.into_inner())
261            .is_new = true;
262    }
263
264    /// Check if this entity root is marked as newly created.
265    pub fn is_new(&self) -> bool {
266        self.inner
267            .lock()
268            .unwrap_or_else(|e| e.into_inner())
269            .is_new
270    }
271
272    /// Store the original record when loaded from DB.
273    pub fn set_original_record(&self, record: Record) {
274        self.inner
275            .lock()
276            .unwrap_or_else(|e| e.into_inner())
277            .original_record = Some(record);
278    }
279
280    /// Retrieve the original record.
281    pub fn original_record(&self) -> Option<Record> {
282        self.inner
283            .lock()
284            .unwrap_or_else(|e| e.into_inner())
285            .original_record
286            .clone()
287    }
288
289    /// Mark an entity as deleted. The next `save()` call will treat this entity
290    /// as a Remove operation in the graph save pipeline.
291    /// Any pending field changes for this entity are cleared — they are irrelevant
292    /// when the entity is being deleted.
293    pub fn mark_as_delete(&self, key: EntityKey) {
294        let mut ctx = self.inner.lock().unwrap_or_else(|e| e.into_inner());
295        ctx.change_sets.clear_entity(&key);
296        ctx.deleted_keys.insert(key);
297    }
298
299    /// Check whether an entity has been marked for deletion.
300    pub fn is_marked_as_delete(&self, key: &EntityKey) -> bool {
301        self.inner
302            .lock()
303            .unwrap_or_else(|e| e.into_inner())
304            .deleted_keys
305            .contains(key)
306    }
307
308    /// Get the set of field names that have been modified for the given entity key.
309    /// This is the Rust equivalent of Java's `entity.getUpdatedProperties()`.
310    pub fn changed_field_names(&self, key: &EntityKey) -> BTreeSet<String> {
311        self.inner
312            .lock()
313            .unwrap_or_else(|e| e.into_inner())
314            .change_sets
315            .changed_field_names(key)
316    }
317}