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 fn save<'a>(
235 self,
236 ctx: &'a UserContext,
237 ) -> Pin<Box<dyn Future<Output = Result<GraphNode, RuntimeError>> + Send + 'a>>;
238}
239
240impl<T> AuditedSaveExt for teaql_core::Audited<T>
241where
242 T: Entity + Send + 'static,
243{
244 fn save<'a>(
245 self,
246 ctx: &'a UserContext,
247 ) -> Pin<Box<dyn Future<Output = Result<GraphNode, RuntimeError>> + Send + 'a>> {
248 Box::pin(async move {
249 let entity_name = T::entity_descriptor().name;
250 let entity = self.into_entity(); let node = graph_node_from_entity(ctx, entity)?;
252 let saver = ctx
253 .require_resource::<Arc<dyn DynGraphSaver>>()
254 .map_err(|e| {
255 RuntimeError::Graph(format!(
256 "no DynGraphSaver registered — did you call register_executor()? ({})",
257 e
258 ))
259 })?;
260 saver.save_graph_dyn(ctx, node).await
261 })
262 }
263}
264
265#[doc(hidden)]
272pub async fn save_audited_ledger_entity<T>(
273 audited: teaql_core::Audited<T>,
274 ctx: &UserContext,
275) -> Result<GraphNode, RuntimeError>
276where
277 T: crate::LedgerEntity + Send + 'static,
278{
279 let entity_name = T::entity_descriptor().name;
280 let entity = audited.into_entity();
281 let root = entity.entity_root();
282 let node = graph_node_from_entity(ctx, entity)?;
283 let saver = ctx
284 .require_resource::<Arc<dyn DynGraphSaver>>()
285 .map_err(|e| {
286 RuntimeError::Graph(format!(
287 "no DynGraphSaver registered — did you call register_executor()? ({e})"
288 ))
289 })?;
290
291 if let Some(root) = root {
292 let has_ledger_changes = !root.current_change_set().changes().is_empty()
293 || !root.deleted_keys().is_empty()
294 || !root.new_keys().is_empty();
295 if has_ledger_changes {
296 return saver.save_ledger_dyn(ctx, node, root).await;
297 }
298 }
299
300 saver.save_graph_dyn(ctx, node).await
301}