Skip to main content

teaql_runtime/
entity_save.rs

1use std::collections::BTreeSet;
2use std::future::Future;
3use std::marker::PhantomData;
4use std::pin::Pin;
5use std::sync::Arc;
6
7use teaql_core::{Entity, MutationValues, Value};
8
9use crate::{DataServiceError, GraphNode, GraphOperation, RuntimeError, UserContext};
10
11// ---------------------------------------------------------------------------
12// DynGraphSaver — type-erased graph save capability
13// ---------------------------------------------------------------------------
14
15/// Object-safe trait for saving a [`GraphNode`] tree to the database.
16///
17/// A concrete implementation is registered in [`UserContext`] during setup so
18/// that [`Audited::save`] can persist entities without exposing the underlying
19/// executor type to business code.
20pub(crate) trait DynGraphSaver: Send + Sync {
21    fn save_graph_dyn<'a>(
22        &'a self,
23        context: &'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        context: &'a UserContext,
30        node: GraphNode,
31        root: crate::EntityRoot,
32    ) -> Pin<Box<dyn Future<Output = Result<GraphNode, RuntimeError>> + Send + 'a>>;
33}
34
35/// Marker struct that implements [`DynGraphSaver`] for a specific executor type `E`.
36///
37/// `E` is the full executor type (e.g. `SqlDataServiceExecutor<SqliteDialect, …>`).
38/// The struct itself is zero-sized; the actual executor is retrieved from
39/// [`UserContext`] at call time.
40pub(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        context: &'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 = context
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        context: &'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 = context
86                .entity_data_service::<E>(&entity)
87                .map_err(|e| RuntimeError::Graph(e.to_string()))?;
88            let generated_ids = eds
89                .execute_ledger_plan_internal(root.clone())
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 = context.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                if let Some(changes) = root.current_change_set().changes().get(&root_key) {
108                    for (field, value) in changes {
109                        node.values.insert(field.clone(), value.clone());
110                    }
111                }
112            }
113            root.clear_committed();
114            Ok(node)
115        })
116    }
117}
118
119// ---------------------------------------------------------------------------
120// Standalone graph-node extraction (no executor needed)
121// ---------------------------------------------------------------------------
122
123/// Convert a typed entity into a [`GraphNode`] tree.
124///
125/// This only requires metadata (entity descriptors) from the [`UserContext`],
126/// **not** the database executor.  It is the standalone equivalent of
127/// [`EntityDataService::graph_node_from_entity`].
128pub fn graph_node_from_entity<T: Entity>(
129    context: &UserContext,
130    entity: T,
131) -> Result<GraphNode, RuntimeError> {
132    let descriptor = T::entity_descriptor();
133    let dirty_fields = entity.dirty_fields();
134    let original_values = entity.original_values();
135    let is_deleted = entity.is_marked_as_delete();
136    let comment = entity.get_comment();
137    let mut node = graph_node_from_values(context, &descriptor.name, entity.into_values())?;
138    node.dirty_fields = dirty_fields;
139    node.original_values = original_values.map(Into::into);
140    if is_deleted {
141        node.operation = GraphOperation::Remove;
142        node.relations.clear();
143    }
144    if let Some(c) = comment {
145        node.set_comment(c);
146    }
147    Ok(node)
148}
149
150/// Recursively convert entity mutation values into a [`GraphNode`] tree.
151///
152/// Relations are resolved via the entity descriptors stored in `context`.
153fn graph_node_from_values(
154    context: &UserContext,
155    entity: &str,
156    values: MutationValues,
157) -> Result<GraphNode, RuntimeError> {
158    let descriptor = context.require_entity(entity)?;
159    let mut node = GraphNode::new(entity);
160
161    for (field, value) in values {
162        if field == "_comment" {
163            if let Value::Text(comment) = value {
164                node.set_comment(comment);
165            }
166            continue;
167        }
168        if field == "_dirty_fields" {
169            if let Value::List(fields) = value {
170                let mut dirty = BTreeSet::new();
171                for f in fields {
172                    if let Value::Text(t) = f {
173                        dirty.insert(t);
174                    }
175                }
176                node.dirty_fields = Some(dirty);
177            }
178            continue;
179        }
180        if field == "_original_values" {
181            if let Value::Object(orig) = value {
182                node.original_values = Some(orig.into());
183            }
184            continue;
185        }
186        let Some(relation) = descriptor.relation_by_name(&field) else {
187            node.values.insert(field, value);
188            continue;
189        };
190
191        match value {
192            Value::Null => {
193                node.relations.entry(field).or_default();
194            }
195            Value::Object(record) => {
196                let child =
197                    graph_node_from_values(context, &relation.target_entity, record.into())?;
198                node.relations.entry(field).or_default().push(child);
199            }
200            Value::List(values) => {
201                let children = node.relations.entry(field.clone()).or_default();
202                for value in values {
203                    let Value::Object(record) = value else {
204                        return Err(RuntimeError::Graph(format!(
205                            "relation {}.{} expects object children, got {:?}",
206                            entity, field, value
207                        )));
208                    };
209                    children.push(graph_node_from_values(
210                        context,
211                        &relation.target_entity,
212                        record.into(),
213                    )?);
214                }
215            }
216            other => {
217                return Err(RuntimeError::Graph(format!(
218                    "relation {}.{} expects object/list/null, got {:?}",
219                    entity, field, other
220                )));
221            }
222        }
223    }
224
225    Ok(node)
226}
227
228// ---------------------------------------------------------------------------
229// AuditedSaveExt — the `.save(&context)` method on `Audited<T>`
230// ---------------------------------------------------------------------------
231
232/// Extension trait that provides the `.save(&context)` method on [`Audited<T>`](teaql_core::Audited).
233///
234/// # Example
235/// ```ignore
236/// use teaql_runtime::AuditedSaveExt;
237///
238/// school.audit_as("创建学校").save(&context).await?;
239/// ```
240pub trait AuditedSaveExt {
241    type Entity;
242
243    fn save<'a>(
244        self,
245        context: &'a UserContext,
246    ) -> Pin<Box<dyn Future<Output = Result<Self::Entity, RuntimeError>> + Send + 'a>>;
247}
248
249impl<T> AuditedSaveExt for teaql_core::Audited<T>
250where
251    T: Entity + Send + 'static,
252{
253    type Entity = T;
254
255    fn save<'a>(
256        self,
257        context: &'a UserContext,
258    ) -> Pin<Box<dyn Future<Output = Result<Self::Entity, RuntimeError>> + Send + 'a>> {
259        Box::pin(async move {
260            let entity_name = T::entity_descriptor().name;
261            let entity = self.into_entity(); // applies comment onto the entity
262            let node = graph_node_from_entity(context, entity)?;
263            let saver = context
264                .require_resource::<Arc<dyn DynGraphSaver>>()
265                .map_err(|e| {
266                    RuntimeError::Graph(format!(
267                        "no DynGraphSaver registered — did you call register_executor()? ({})",
268                        e
269                    ))
270                })?;
271            let saved = saver.save_graph_dyn(context, node).await?;
272            T::from_compact_row(teaql_core::CompactRow::from_map(saved.values.into()))
273                .map_err(|e| RuntimeError::Graph(e.to_string()))
274        })
275    }
276}
277
278/// Persist an audited generated entity, including pending ledger changes that
279/// may span multiple related entities sharing the same [`EntityRoot`](crate::EntityRoot).
280///
281/// Generated service crates use this as the implementation behind
282/// `entity.audit_as("why").save(&context)`. The audited wrapper is required by the
283/// function signature; no unaudited entity write entry point is exposed.
284#[doc(hidden)]
285pub async fn save_audited_ledger_entity<T>(
286    audited: teaql_core::Audited<T>,
287    context: &UserContext,
288) -> Result<T, RuntimeError>
289where
290    T: crate::LedgerEntity + Send + 'static,
291{
292    let entity_name = T::entity_descriptor().name;
293    let entity = audited.into_entity();
294    let root = entity.entity_root();
295    let node = graph_node_from_entity(context, entity)?;
296    let saver = context
297        .require_resource::<Arc<dyn DynGraphSaver>>()
298        .map_err(|e| {
299            RuntimeError::Graph(format!(
300                "no DynGraphSaver registered — did you call register_executor()? ({e})"
301            ))
302        })?;
303
304    if let Some(root) = root {
305        let has_ledger_changes = !root.current_change_set().changes().is_empty()
306            || !root.deleted_keys().is_empty()
307            || !root.new_keys().is_empty();
308        if has_ledger_changes {
309            let saved = saver.save_ledger_dyn(context, node, root).await?;
310            return T::from_compact_row(teaql_core::CompactRow::from_map(saved.values.into()))
311                .map_err(|e| RuntimeError::Graph(e.to_string()));
312        }
313    }
314
315    let saved = saver.save_graph_dyn(context, node).await?;
316    T::from_compact_row(teaql_core::CompactRow::from_map(saved.values.into()))
317        .map_err(|e| RuntimeError::Graph(e.to_string()))
318}