teaql_runtime/
entity_runtime.rs1use 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 pub fn clear_entity(&mut self, key: &EntityKey) {
90 self.changes.remove(key);
91 }
92
93 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 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 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 comment: Option<String>,
167 deleted_keys: BTreeSet<EntityKey>,
170 is_new: bool,
172 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 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 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 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 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 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 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 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 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 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}