teaql-runtime 4.2.0

TeaQL core, SQL, runtime, dialect, and macro crates for model-driven data access
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;

use teaql_core::{Record, TraceNode, Value};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GraphOperation {
    Upsert,
    Create,
    Reference,
    Remove,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum GraphMutationKind {
    Create,
    Update,
    Delete,
    Reference,
}

impl GraphMutationKind {
    pub fn for_update(is_update: bool) -> Self {
        match is_update {
            true => Self::Update,
            false => Self::Create,
        }
    }
}

/// A persistent linked-list token for hierarchical trace context.
///
/// Each token holds the trace info for one graph node and an `Arc` pointer
/// to its parent's token. The full trace chain is only materialized when
/// explicitly requested via [`recover_trace_chain()`], giving us zero-cost
/// propagation during the flatten phase.
#[derive(Debug, Clone, PartialEq)]
pub struct TraceScopeToken {
    /// Shared pointer to the parent scope (zero-copy link).
    pub parent: Option<Arc<TraceScopeToken>>,
    /// The trace metadata for this scope level.
    pub track: TraceNode,
    /// The item_index of the PlanItem that created this scope (for debugging).
    pub node_index: u64,
}

impl TraceScopeToken {
    /// Lazily recover the full trace chain by walking the parent pointers.
    /// Only called when an event consumer actually needs the chain.
    pub fn recover_trace_chain(&self) -> Vec<TraceNode> {
        let mut chain = Vec::new();
        let mut current: Option<&TraceScopeToken> = Some(self);
        while let Some(token) = current {
            if !token.track.comment.is_empty() {
                chain.push(token.track.clone());
            }
            current = token.parent.as_deref();
        }
        chain.reverse();
        chain
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct GraphMutationPlanItem {
    pub entity: String,
    pub kind: GraphMutationKind,
    pub values: Record,
    pub update_fields: Vec<String>,
    /// Monotonically increasing index assigned at push time (for debugging).
    pub item_index: u64,
    /// Lazy trace context — only materialized into a Vec<TraceNode> on demand.
    pub scope_token: Option<Arc<TraceScopeToken>>,
    pub old_values: Option<Record>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct GraphMutationBatch {
    pub entity: String,
    pub kind: GraphMutationKind,
    pub update_fields: Vec<String>,
    pub items: Vec<GraphMutationPlanItem>,
}

#[derive(Debug, Clone, PartialEq, Default)]
pub struct GraphMutationPlan {
    pub planned_root: Option<GraphNode>,
    pub items: Vec<GraphMutationPlanItem>,
    pub batches: Vec<GraphMutationBatch>,
    /// Auto-incrementing counter for item_index assignment.
    pub next_item_index: u64,
    /// Keep track of visited nodes to avoid infinite loops and redundant updates
    pub visited_nodes: std::collections::HashSet<(String, String)>,
}

impl GraphMutationPlan {
    pub fn push(
        &mut self,
        entity: impl Into<String>,
        kind: GraphMutationKind,
        values: Record,
        update_fields: Vec<String>,
        scope_token: Option<Arc<TraceScopeToken>>,
        old_values: Option<Record>,
    ) {
        let index = self.next_item_index;
        self.next_item_index += 1;
        self.items.push(GraphMutationPlanItem {
            entity: entity.into(),
            kind,
            values,
            update_fields,
            item_index: index,
            scope_token,
            old_values,
        });
    }

    pub fn rebuild_batches(&mut self) {
        let mut grouped: BTreeMap<
            (String, GraphMutationKind, Vec<String>),
            Vec<GraphMutationPlanItem>,
        > = BTreeMap::new();
        for item in &self.items {
            let update_fields = match item.kind {
                GraphMutationKind::Update => item.update_fields.clone(),
                _ => Vec::new(),
            };
            grouped
                .entry((item.entity.clone(), item.kind, update_fields))
                .or_default()
                .push(item.clone());
        }
        self.batches = grouped
            .into_iter()
            .map(
                |((entity, kind, update_fields), items)| GraphMutationBatch {
                    entity,
                    kind,
                    update_fields,
                    items,
                },
            )
            .collect();
    }

    pub fn grouped_counts(&self) -> BTreeMap<(String, GraphMutationKind), usize> {
        let mut counts = BTreeMap::new();
        for batch in &self.batches {
            *counts
                .entry((batch.entity.clone(), batch.kind))
                .or_insert(0) += batch.items.len();
        }
        counts
    }

    pub fn batch_count(&self) -> usize {
        self.batches.len()
    }

    pub fn len(&self) -> usize {
        self.items.len()
    }

    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }
}

pub fn sorted_update_fields(
    values: &Record,
    excluded: impl IntoIterator<Item = String>,
) -> Vec<String> {
    let excluded = excluded.into_iter().collect::<BTreeSet<_>>();
    values
        .keys()
        .filter(|field| !excluded.contains(*field))
        .cloned()
        .collect()
}

#[derive(Debug, Clone, PartialEq)]
pub struct GraphNode {
    pub entity: String,
    pub values: Record,
    pub relations: BTreeMap<String, Vec<GraphNode>>,
    pub operation: GraphOperation,
    /// Annotation comment: carries business intent metadata through graph save.
    /// Not persisted to the database — used for observability (SQL logs, audit trails).
    pub comment: Option<String>,
    /// Fields modified via `update_*()` methods (dirty tracking).
    /// `None` = all fields (new entity or no tracking available).
    /// `Some(set)` = only these fields were modified — UPDATE should only include them.
    /// This is the Rust equivalent of Java's `entity.getUpdatedProperties()`.
    pub dirty_fields: Option<BTreeSet<String>>,
    /// L1 Cache snapshot of the entity values exactly as they were loaded from the database.
    /// Used by the Event Engine to eliminate redundant old_value queries during auditing.
    pub original_values: Option<Record>,
}

impl GraphNode {
    pub fn new(entity: impl Into<String>) -> Self {
        Self {
            entity: entity.into(),
            values: Record::new(),
            relations: BTreeMap::new(),
            operation: GraphOperation::Upsert,
            comment: None,
            dirty_fields: None,
            original_values: None,
        }
    }

    pub fn operation(mut self, operation: GraphOperation) -> Self {
        self.operation = operation;
        self
    }

    pub fn reference(mut self) -> Self {
        self.operation = GraphOperation::Reference;
        self
    }

    pub fn remove(mut self) -> Self {
        self.operation = GraphOperation::Remove;
        self
    }

    pub fn value(mut self, field: impl Into<String>, value: impl Into<Value>) -> Self {
        self.values.insert(field.into(), value.into());
        self
    }

    pub fn relation(mut self, name: impl Into<String>, node: GraphNode) -> Self {
        self.relations.entry(name.into()).or_default().push(node);
        self
    }

    pub fn relations(
        mut self,
        name: impl Into<String>,
        nodes: impl IntoIterator<Item = GraphNode>,
    ) -> Self {
        self.relations.entry(name.into()).or_default().extend(nodes);
        self
    }

    pub fn id(&self) -> Option<&Value> {
        self.values.get("id")
    }

    /// Set an annotation comment on this graph node.
    /// The comment propagates through the graph save process for observability.
    pub fn comment(mut self, comment: impl Into<String>) -> Self {
        self.comment = Some(comment.into());
        self
    }

    /// Set an annotation comment by mutable reference.
    pub fn set_comment(&mut self, comment: impl Into<String>) {
        self.comment = Some(comment.into());
    }
}

// ---------------------------------------------------------------------------
// Hierarchical Comment Propagation (Scoped Cons List)
// ---------------------------------------------------------------------------

/// A stack-allocated scope node forming a parent-pointer cons list.
///
/// Each node lives on the call stack of the recursive graph save function.
/// Child nodes hold a `&'a` reference to their parent's stack frame,
/// giving us thread-safe, lock-free, zero-overhead hierarchical comment tracking.
#[derive(Debug)]
pub struct ScopedCommentNode<'a> {
    /// Reference to the parent scope (lives on the caller's stack frame)
    pub parent: Option<&'a ScopedCommentNode<'a>>,
    pub track: teaql_core::TraceNode,
}

impl<'a> ScopedCommentNode<'a> {
    pub fn to_trace_chain(&self) -> Vec<teaql_core::TraceNode> {
        let mut chain = Vec::new();
        let mut current: Option<&ScopedCommentNode<'_>> = Some(self);

        while let Some(node) = current {
            if !node.track.comment.is_empty() {
                chain.push(node.track.clone());
            }
            current = node.parent;
        }

        chain.reverse();
        chain
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_hierarchical_trace_chain_recovery() {
        let root_trace = TraceNode {
            entity_type: "User".to_string(),
            entity_id: Some(1),
            comment: "Create User".to_string(),
        };

        let child_trace = TraceNode {
            entity_type: "Profile".to_string(),
            entity_id: None,
            comment: "Create Profile".to_string(),
        };

        let empty_comment_trace = TraceNode {
            entity_type: "AuditLog".to_string(),
            entity_id: None,
            comment: "".to_string(),
        };

        // Test ScopedCommentNode
        let root_scope = ScopedCommentNode {
            parent: None,
            track: root_trace.clone(),
        };
        let child_scope = ScopedCommentNode {
            parent: Some(&root_scope),
            track: child_trace.clone(),
        };
        let empty_scope = ScopedCommentNode {
            parent: Some(&child_scope),
            track: empty_comment_trace.clone(),
        };

        let chain = empty_scope.to_trace_chain();
        assert_eq!(chain.len(), 2);
        assert_eq!(chain[0], root_trace);
        assert_eq!(chain[1], child_trace);

        // Test TraceScopeToken
        let root_token = Arc::new(TraceScopeToken {
            parent: None,
            track: root_trace.clone(),
            node_index: 0,
        });
        let child_token = Arc::new(TraceScopeToken {
            parent: Some(root_token),
            track: child_trace.clone(),
            node_index: 1,
        });
        let empty_token = Arc::new(TraceScopeToken {
            parent: Some(child_token),
            track: empty_comment_trace,
            node_index: 2,
        });

        let chain = empty_token.recover_trace_chain();
        assert_eq!(chain.len(), 2);
        assert_eq!(chain[0], root_trace);
        assert_eq!(chain[1], child_trace);
    }

    #[test]
    fn test_graph_mutation_plan_batching_keys_and_counts() {
        let mut plan = GraphMutationPlan::default();

        // Push 2 creates for User
        plan.push(
            "User",
            GraphMutationKind::Create,
            Record::new(),
            vec![],
            None,
            None,
        );
        plan.push(
            "User",
            GraphMutationKind::Create,
            Record::new(),
            vec![],
            None,
            None,
        );

        // Push 2 updates for User with same fields
        plan.push(
            "User",
            GraphMutationKind::Update,
            Record::new(),
            vec!["name".to_string()],
            None,
            None,
        );
        plan.push(
            "User",
            GraphMutationKind::Update,
            Record::new(),
            vec!["name".to_string()],
            None,
            None,
        );

        // Push 1 update for User with different fields (should be separate batch)
        plan.push(
            "User",
            GraphMutationKind::Update,
            Record::new(),
            vec!["email".to_string()],
            None,
            None,
        );

        // Push 1 create for Profile
        plan.push(
            "Profile",
            GraphMutationKind::Create,
            Record::new(),
            vec![],
            None,
            None,
        );

        assert_eq!(plan.len(), 6);

        // Rebuild batches
        plan.rebuild_batches();

        // We expect 4 batches:
        // 1. User Create (2 items)
        // 2. User Update ["email"] (1 item)
        // 3. User Update ["name"] (2 items)
        // 4. Profile Create (1 item)
        assert_eq!(plan.batch_count(), 4);

        let counts = plan.grouped_counts();
        assert_eq!(counts.len(), 3);
        assert_eq!(
            counts.get(&("User".to_string(), GraphMutationKind::Create)),
            Some(&2)
        );
        assert_eq!(
            counts.get(&("User".to_string(), GraphMutationKind::Update)),
            Some(&3)
        );
        assert_eq!(
            counts.get(&("Profile".to_string(), GraphMutationKind::Create)),
            Some(&1)
        );
    }
}