teaql_runtime/
entity_save.rs1use std::collections::BTreeSet;
2use std::future::Future;
3use std::marker::PhantomData;
4use std::pin::Pin;
5use std::sync::Arc;
6
7use teaql_core::{Entity, Record, Value};
8
9use crate::{DataServiceError, GraphNode, GraphOperation, RuntimeError, UserContext};
10
11pub(crate) trait DynGraphSaver: Send + Sync {
21 fn save_graph_dyn<'a>(
22 &'a self,
23 ctx: &'a UserContext,
24 node: GraphNode,
25 ) -> Pin<Box<dyn Future<Output = Result<GraphNode, RuntimeError>> + Send + 'a>>;
26
27 fn save_ledger_dyn<'a>(
28 &'a self,
29 ctx: &'a UserContext,
30 node: GraphNode,
31 root: crate::EntityRoot,
32 ) -> Pin<Box<dyn Future<Output = Result<GraphNode, RuntimeError>> + Send + 'a>>;
33}
34
35pub(crate) struct GraphSaverFor<E> {
41 _marker: PhantomData<fn() -> E>,
42}
43
44impl<E> GraphSaverFor<E> {
45 pub(crate) fn new() -> Self {
46 Self {
47 _marker: PhantomData,
48 }
49 }
50}
51
52impl<E> DynGraphSaver for GraphSaverFor<E>
53where
54 E: teaql_data_service::QueryExecutor
55 + teaql_data_service::MutationExecutor
56 + Send
57 + Sync
58 + 'static,
59{
60 fn save_graph_dyn<'a>(
61 &'a self,
62 ctx: &'a UserContext,
63 node: GraphNode,
64 ) -> Pin<Box<dyn Future<Output = Result<GraphNode, RuntimeError>> + Send + 'a>> {
65 Box::pin(async move {
66 let entity = node.entity.clone();
67 let eds = ctx
68 .entity_data_service::<E>(entity)
69 .map_err(|e| RuntimeError::Graph(e.to_string()))?;
70 eds.save_graph_internal(node).await.map_err(|e| match e {
71 DataServiceError::Runtime(r) => r,
72 other => RuntimeError::Graph(other.to_string()),
73 })
74 })
75 }
76
77 fn save_ledger_dyn<'a>(
78 &'a self,
79 ctx: &'a UserContext,
80 mut node: GraphNode,
81 root: crate::EntityRoot,
82 ) -> Pin<Box<dyn Future<Output = Result<GraphNode, RuntimeError>> + Send + 'a>> {
83 Box::pin(async move {
84 let entity = node.entity.clone();
85 let eds = ctx
86 .entity_data_service::<E>(&entity)
87 .map_err(|e| RuntimeError::Graph(e.to_string()))?;
88 let generated_ids =
89 eds.execute_ledger_plan_internal(root)
90 .await
91 .map_err(|e| match e {
92 DataServiceError::Runtime(r) => r,
93 other => RuntimeError::Graph(other.to_string()),
94 })?;
95
96 let descriptor = ctx.require_entity(&entity).unwrap();
97 if let Some(id_prop) = descriptor.id_property() {
98 let current_id = node
99 .values
100 .get(&id_prop.name)
101 .cloned()
102 .unwrap_or(Value::I64(0));
103 let root_key = crate::EntityKey::new(entity.clone(), current_id);
104 if let Some(new_id) = generated_ids.get(&root_key) {
105 node.values.insert(id_prop.name.clone(), new_id.clone());
106 }
107 }
108 Ok(node)
109 })
110 }
111}
112
113pub fn graph_node_from_entity<T: Entity>(
123 ctx: &UserContext,
124 entity: T,
125) -> Result<GraphNode, RuntimeError> {
126 let descriptor = T::entity_descriptor();
127 let dirty_fields = entity.dirty_fields();
128 let original_values = entity.original_values();
129 let is_deleted = entity.is_marked_as_delete();
130 let comment = entity.get_comment();
131 let mut node = graph_node_from_record(ctx, &descriptor.name, entity.into_record())?;
132 node.dirty_fields = dirty_fields;
133 node.original_values = original_values;
134 if is_deleted {
135 node.operation = GraphOperation::Remove;
136 node.relations.clear();
137 }
138 if let Some(c) = comment {
139 node.set_comment(c);
140 }
141 Ok(node)
142}
143
144fn graph_node_from_record(
148 ctx: &UserContext,
149 entity: &str,
150 record: Record,
151) -> Result<GraphNode, RuntimeError> {
152 let descriptor = ctx.require_entity(entity)?;
153 let mut node = GraphNode::new(entity);
154
155 for (field, value) in record {
156 if field == "_comment" {
157 if let Value::Text(comment) = value {
158 node.set_comment(comment);
159 }
160 continue;
161 }
162 if field == "_dirty_fields" {
163 if let Value::List(fields) = value {
164 let mut dirty = BTreeSet::new();
165 for f in fields {
166 if let Value::Text(t) = f {
167 dirty.insert(t);
168 }
169 }
170 node.dirty_fields = Some(dirty);
171 }
172 continue;
173 }
174 if field == "_original_values" {
175 if let Value::Object(orig) = value {
176 node.original_values = Some(orig);
177 }
178 continue;
179 }
180 let Some(relation) = descriptor.relation_by_name(&field) else {
181 node.values.insert(field, value);
182 continue;
183 };
184
185 match value {
186 Value::Null => {
187 node.relations.entry(field).or_default();
188 }
189 Value::Object(record) => {
190 let child = graph_node_from_record(ctx, &relation.target_entity, record)?;
191 node.relations.entry(field).or_default().push(child);
192 }
193 Value::List(values) => {
194 let children = node.relations.entry(field.clone()).or_default();
195 for value in values {
196 let Value::Object(record) = value else {
197 return Err(RuntimeError::Graph(format!(
198 "relation {}.{} expects object children, got {:?}",
199 entity, field, value
200 )));
201 };
202 children.push(graph_node_from_record(
203 ctx,
204 &relation.target_entity,
205 record,
206 )?);
207 }
208 }
209 other => {
210 return Err(RuntimeError::Graph(format!(
211 "relation {}.{} expects object/list/null, got {:?}",
212 entity, field, other
213 )));
214 }
215 }
216 }
217
218 Ok(node)
219}
220
221pub trait AuditedSaveExt {
234 type Entity;
235
236 fn save<'a>(
237 self,
238 ctx: &'a UserContext,
239 ) -> Pin<Box<dyn Future<Output = Result<Self::Entity, RuntimeError>> + Send + 'a>>;
240}
241
242impl<T> AuditedSaveExt for teaql_core::Audited<T>
243where
244 T: Entity + Send + 'static,
245{
246 type Entity = T;
247
248 fn save<'a>(
249 self,
250 ctx: &'a UserContext,
251 ) -> Pin<Box<dyn Future<Output = Result<Self::Entity, RuntimeError>> + Send + 'a>> {
252 Box::pin(async move {
253 let entity_name = T::entity_descriptor().name;
254 let entity = self.into_entity(); let node = graph_node_from_entity(ctx, entity)?;
256 let saver = ctx
257 .require_resource::<Arc<dyn DynGraphSaver>>()
258 .map_err(|e| {
259 RuntimeError::Graph(format!(
260 "no DynGraphSaver registered — did you call register_executor()? ({})",
261 e
262 ))
263 })?;
264 let saved = saver.save_graph_dyn(ctx, node).await?;
265 T::from_record(saved.values).map_err(|e| RuntimeError::Graph(e.to_string()))
266 })
267 }
268}
269
270#[doc(hidden)]
277pub async fn save_audited_ledger_entity<T>(
278 audited: teaql_core::Audited<T>,
279 ctx: &UserContext,
280) -> Result<T, RuntimeError>
281where
282 T: crate::LedgerEntity + Send + 'static,
283{
284 let entity_name = T::entity_descriptor().name;
285 let entity = audited.into_entity();
286 let root = entity.entity_root();
287 let node = graph_node_from_entity(ctx, entity)?;
288 let saver = ctx
289 .require_resource::<Arc<dyn DynGraphSaver>>()
290 .map_err(|e| {
291 RuntimeError::Graph(format!(
292 "no DynGraphSaver registered — did you call register_executor()? ({e})"
293 ))
294 })?;
295
296 if let Some(root) = root {
297 let has_ledger_changes = !root.current_change_set().changes().is_empty()
298 || !root.deleted_keys().is_empty()
299 || !root.new_keys().is_empty();
300 if has_ledger_changes {
301 let saved = saver.save_ledger_dyn(ctx, node, root).await?;
302 return T::from_record(saved.values).map_err(|e| RuntimeError::Graph(e.to_string()));
303 }
304 }
305
306 let saved = saver.save_graph_dyn(ctx, node).await?;
307 T::from_record(saved.values).map_err(|e| RuntimeError::Graph(e.to_string()))
308}