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 = graph_node_from_values(context, &relation.target_entity, record.into())?;
197                node.relations.entry(field).or_default().push(child);
198            }
199            Value::List(values) => {
200                let children = node.relations.entry(field.clone()).or_default();
201                for value in values {
202                    let Value::Object(record) = value else {
203                        return Err(RuntimeError::Graph(format!(
204                            "relation {}.{} expects object children, got {:?}",
205                            entity, field, value
206                        )));
207                    };
208                    children.push(graph_node_from_values(
209                        context,
210                        &relation.target_entity,
211                        record.into(),
212                    )?);
213                }
214            }
215            other => {
216                return Err(RuntimeError::Graph(format!(
217                    "relation {}.{} expects object/list/null, got {:?}",
218                    entity, field, other
219                )));
220            }
221        }
222    }
223
224    Ok(node)
225}
226
227// ---------------------------------------------------------------------------
228// AuditedSaveExt — the `.save(&context)` method on `Audited<T>`
229// ---------------------------------------------------------------------------
230
231/// Extension trait that provides the `.save(&context)` method on [`Audited<T>`](teaql_core::Audited).
232///
233/// # Example
234/// ```ignore
235/// use teaql_runtime::AuditedSaveExt;
236///
237/// school.audit_as("创建学校").save(&context).await?;
238/// ```
239pub trait AuditedSaveExt {
240    type Entity;
241
242    fn save<'a>(
243        self,
244        context: &'a UserContext,
245    ) -> Pin<Box<dyn Future<Output = Result<Self::Entity, RuntimeError>> + Send + 'a>>;
246}
247
248impl<T> AuditedSaveExt for teaql_core::Audited<T>
249where
250    T: Entity + Send + 'static,
251{
252    type Entity = T;
253
254    fn save<'a>(
255        self,
256        context: &'a UserContext,
257    ) -> Pin<Box<dyn Future<Output = Result<Self::Entity, RuntimeError>> + Send + 'a>> {
258        Box::pin(async move {
259            let entity_name = T::entity_descriptor().name;
260            let entity = self.into_entity(); // applies comment onto the entity
261            let node = graph_node_from_entity(context, entity)?;
262            let saver = context
263                .require_resource::<Arc<dyn DynGraphSaver>>()
264                .map_err(|e| {
265                    RuntimeError::Graph(format!(
266                        "no DynGraphSaver registered — did you call register_executor()? ({})",
267                        e
268                    ))
269                })?;
270            let saved = saver.save_graph_dyn(context, node).await?;
271            T::from_compact_row(teaql_core::CompactRow::from_map(saved.values.into()))
272                .map_err(|e| RuntimeError::Graph(e.to_string()))
273        })
274    }
275}
276
277/// Persist an audited generated entity, including pending ledger changes that
278/// may span multiple related entities sharing the same [`EntityRoot`](crate::EntityRoot).
279///
280/// Generated service crates use this as the implementation behind
281/// `entity.audit_as("why").save(&context)`. The audited wrapper is required by the
282/// function signature; no unaudited entity write entry point is exposed.
283#[doc(hidden)]
284pub async fn save_audited_ledger_entity<T>(
285    audited: teaql_core::Audited<T>,
286    context: &UserContext,
287) -> Result<T, RuntimeError>
288where
289    T: crate::LedgerEntity + Send + 'static,
290{
291    let entity_name = T::entity_descriptor().name;
292    let entity = audited.into_entity();
293    let root = entity.entity_root();
294    let node = graph_node_from_entity(context, entity)?;
295    let saver = context
296        .require_resource::<Arc<dyn DynGraphSaver>>()
297        .map_err(|e| {
298            RuntimeError::Graph(format!(
299                "no DynGraphSaver registered — did you call register_executor()? ({e})"
300            ))
301        })?;
302
303    if let Some(root) = root {
304        let has_ledger_changes = !root.current_change_set().changes().is_empty()
305            || !root.deleted_keys().is_empty()
306            || !root.new_keys().is_empty();
307        if has_ledger_changes {
308            let saved = saver.save_ledger_dyn(context, node, root).await?;
309            return T::from_compact_row(teaql_core::CompactRow::from_map(saved.values.into()))
310                .map_err(|e| RuntimeError::Graph(e.to_string()));
311        }
312    }
313
314    let saved = saver.save_graph_dyn(context, node).await?;
315    T::from_compact_row(teaql_core::CompactRow::from_map(saved.values.into()))
316        .map_err(|e| RuntimeError::Graph(e.to_string()))
317}