teaql-runtime 4.3.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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
use std::collections::BTreeMap;
use std::sync::Arc;

use teaql_core::{Entity, TeaqlEntity, Value};

use crate::{EntityValues, UserContext};

pub const CHECK_OBJECT_STATUS_FIELD: &str = "__teaql_object_status";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CheckObjectStatus {
    Create,
    Update,
    Unknown,
}

impl CheckObjectStatus {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Create => "create",
            Self::Update => "update",
            Self::Unknown => "unknown",
        }
    }

    pub fn from_values(values: &EntityValues) -> Self {
        match values.get(CHECK_OBJECT_STATUS_FIELD) {
            Some(Value::Text(value)) if value == Self::Create.as_str() => Self::Create,
            Some(Value::Text(value)) if value == Self::Update.as_str() => Self::Update,
            _ => match values.get("id") {
                None | Some(Value::Null) => Self::Create,
                Some(_) => Self::Update,
            },
        }
    }

    pub fn is_create(self) -> bool {
        matches!(self, Self::Create)
    }

    pub fn is_update(self) -> bool {
        matches!(self, Self::Update)
    }
}

impl From<CheckObjectStatus> for Value {
    fn from(value: CheckObjectStatus) -> Self {
        Value::Text(value.as_str().to_owned())
    }
}

pub fn mark_entity_status(values: &mut EntityValues, status: CheckObjectStatus) {
    values.insert(CHECK_OBJECT_STATUS_FIELD.to_owned(), status.into());
}

pub fn clear_entity_status(values: &mut EntityValues) {
    values.remove(CHECK_OBJECT_STATUS_FIELD);
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CheckRule {
    Required,
    InvalidType,
    Min,
    Max,
    MinStringLength,
    MaxStringLength,
    ContextRootMissing,
    ContextRootMismatch,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LocationSegment {
    Member(String),
    Index(usize),
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ObjectLocation {
    segments: Vec<LocationSegment>,
}

impl ObjectLocation {
    pub fn root() -> Self {
        Self::default()
    }

    pub fn hash_root(member: impl Into<String>) -> Self {
        Self::root().member(member)
    }

    pub fn array_root(index: usize) -> Self {
        Self::root().element(index)
    }

    pub fn member(mut self, member: impl Into<String>) -> Self {
        self.segments.push(LocationSegment::Member(member.into()));
        self
    }

    pub fn element(mut self, index: usize) -> Self {
        self.segments.push(LocationSegment::Index(index));
        self
    }

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

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

    /// Canonical casing-neutral path using KSML property names.
    pub fn model_path(&self) -> String {
        self.render_path(|name| name.to_owned())
    }

    /// Rust diagnostic path. KSML snake_case is already idiomatic Rust.
    pub fn native_path(&self) -> String {
        self.render_path(|name| name.to_owned())
    }

    /// RFC 6901 JSON pointer using TeaQL's default lower-camel wire policy.
    pub fn instance_path(&self) -> String {
        self.segments
            .iter()
            .map(|segment| match segment {
                LocationSegment::Member(member) => {
                    format!("/{}", escape_json_pointer(&lower_camel(member)))
                }
                LocationSegment::Index(index) => format!("/{index}"),
            })
            .collect()
    }

    fn render_path(&self, property_name: impl Fn(&str) -> String) -> String {
        let mut result = String::new();
        for segment in &self.segments {
            match segment {
                LocationSegment::Member(member) => {
                    if !result.is_empty() {
                        result.push('.');
                    }
                    result.push_str(&property_name(member));
                }
                LocationSegment::Index(index) => result.push_str(&format!("[{index}]")),
            }
        }
        result
    }
}

fn lower_camel(name: &str) -> String {
    let mut parts = name.split('_');
    let mut result = parts.next().unwrap_or_default().to_owned();
    for part in parts {
        let mut chars = part.chars();
        if let Some(first) = chars.next() {
            result.extend(first.to_uppercase());
            result.extend(chars);
        }
    }
    result
}

fn escape_json_pointer(value: &str) -> String {
    value.replace('~', "~0").replace('/', "~1")
}

impl std::fmt::Display for ObjectLocation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.segments.is_empty() {
            return write!(f, "$");
        }
        let mut first = true;
        for segment in &self.segments {
            match segment {
                LocationSegment::Member(member) => {
                    if !first {
                        write!(f, ".")?;
                    }
                    write!(f, "{member}")?;
                }
                LocationSegment::Index(index) => {
                    write!(f, "[{index}]")?;
                }
            }
            first = false;
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct CheckResult {
    pub rule: CheckRule,
    pub location: ObjectLocation,
    pub input_value: Option<Value>,
    pub system_value: Option<Value>,
    pub message: Option<String>,
}

impl CheckResult {
    pub fn new(rule: CheckRule, location: ObjectLocation) -> Self {
        Self {
            rule,
            location,
            input_value: None,
            system_value: None,
            message: None,
        }
    }

    pub fn required(location: ObjectLocation) -> Self {
        Self::new(CheckRule::Required, location)
    }

    pub fn min(location: ObjectLocation, min: impl Into<Value>, current: impl Into<Value>) -> Self {
        Self::new(CheckRule::Min, location)
            .with_system_value(min)
            .with_input_value(current)
    }

    pub fn max(location: ObjectLocation, max: impl Into<Value>, current: impl Into<Value>) -> Self {
        Self::new(CheckRule::Max, location)
            .with_system_value(max)
            .with_input_value(current)
    }

    pub fn min_str(location: ObjectLocation, min_len: u64, current: impl Into<Value>) -> Self {
        Self::new(CheckRule::MinStringLength, location)
            .with_system_value(min_len)
            .with_input_value(current)
    }

    pub fn max_str(location: ObjectLocation, max_len: u64, current: impl Into<Value>) -> Self {
        Self::new(CheckRule::MaxStringLength, location)
            .with_system_value(max_len)
            .with_input_value(current)
    }

    pub fn with_input_value(mut self, value: impl Into<Value>) -> Self {
        self.input_value = Some(value.into());
        self
    }

    pub fn with_system_value(mut self, value: impl Into<Value>) -> Self {
        self.system_value = Some(value.into());
        self
    }

    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }
}

impl std::fmt::Display for CheckResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.message {
            Some(message) => write!(f, "{message}"),
            None => write!(f, "{}: {:?}", self.location, self.rule),
        }
    }
}

pub type CheckResults = Vec<CheckResult>;

pub trait Checker: Send + Sync {
    fn entity(&self) -> &str;

    fn check_and_fix(
        &self,
        context: &UserContext,
        values: &mut EntityValues,
        location: &ObjectLocation,
        results: &mut CheckResults,
    );

    fn required(
        &self,
        values: &EntityValues,
        field: &str,
        location: &ObjectLocation,
        results: &mut CheckResults,
    ) {
        if matches!(values.get(field), None | Some(Value::Null)) {
            results.push(CheckResult::required(location.clone().member(field)));
        }
    }

    fn min_string_length(
        &self,
        values: &EntityValues,
        field: &str,
        min_len: usize,
        location: &ObjectLocation,
        results: &mut CheckResults,
    ) {
        if let Some(Value::Text(value)) = values.get(field) {
            if value.chars().count() < min_len {
                results.push(CheckResult::min_str(
                    location.clone().member(field),
                    min_len as u64,
                    value.clone(),
                ));
            }
        }
    }

    fn max_string_length(
        &self,
        values: &EntityValues,
        field: &str,
        max_len: usize,
        location: &ObjectLocation,
        results: &mut CheckResults,
    ) {
        if let Some(Value::Text(value)) = values.get(field) {
            if value.chars().count() > max_len {
                results.push(CheckResult::max_str(
                    location.clone().member(field),
                    max_len as u64,
                    value.clone(),
                ));
            }
        }
    }
}

pub trait CheckerRegistry: Send + Sync {
    fn checker(&self, entity: &str) -> Option<Arc<dyn Checker>>;
}

#[derive(Default, Clone)]
pub struct InMemoryCheckerRegistry {
    checkers: BTreeMap<String, Arc<dyn Checker>>,
}

impl InMemoryCheckerRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn register(&mut self, checker: impl Checker + 'static) {
        self.checkers
            .insert(checker.entity().to_owned(), Arc::new(checker));
    }

    pub fn with_checker(mut self, checker: impl Checker + 'static) -> Self {
        self.register(checker);
        self
    }
}

impl CheckerRegistry for InMemoryCheckerRegistry {
    fn checker(&self, entity: &str) -> Option<Arc<dyn Checker>> {
        self.checkers.get(entity).cloned()
    }
}

// ---------------------------------------------------------------------------
// TypedChecker & TypedEntityChecker
// ---------------------------------------------------------------------------

/// Typed version of [`Checker`] that works with concrete entity types (`T`)
/// instead of generic value maps.
///
/// Implement this trait for per-entity checker logic structs, then wrap
/// them in [`TypedEntityChecker`] so they satisfy the [`Checker`] trait
/// expected by [`InMemoryCheckerRegistry`].
pub trait TypedChecker<T>: Send + Sync {
    fn check_and_fix_typed(
        &self,
        context: &UserContext,
        entity: &mut T,
        status: CheckObjectStatus,
        location: &ObjectLocation,
        results: &mut CheckResults,
    );
}

/// Adapter that turns a [`TypedChecker<T>`] into a [`Checker`].
///
/// On [`Checker::check_and_fix`], it:
/// 1. Extracts [`CheckObjectStatus`] from the entity values.
/// 2. Materializes `T` from a compact row.
/// 3. Delegates to [`TypedChecker::check_and_fix_typed`].
/// 4. Serializes the (possibly mutated) `T` back into entity values.
pub struct TypedEntityChecker<T, C> {
    checker: C,
    entity_name: String,
    _marker: std::marker::PhantomData<fn() -> T>,
}

impl<T, C> TypedEntityChecker<T, C>
where
    T: TeaqlEntity,
{
    /// Create a new `TypedEntityChecker` wrapping `checker`.
    pub fn new(checker: C) -> Self {
        let entity_name = T::entity_descriptor().name.clone();
        Self {
            checker,
            entity_name,
            _marker: std::marker::PhantomData,
        }
    }
}

impl<T, C> Checker for TypedEntityChecker<T, C>
where
    T: Entity + TeaqlEntity + Send + Sync + Clone,
    C: TypedChecker<T>,
{
    fn entity(&self) -> &str {
        &self.entity_name
    }

    fn check_and_fix(
        &self,
        context: &UserContext,
        values: &mut EntityValues,
        location: &ObjectLocation,
        results: &mut CheckResults,
    ) {
        let status = CheckObjectStatus::from_values(values);
        // Materializing a partial update necessarily fills omitted Rust fields
        // with their type defaults. Those defaults are only a checker view;
        // they must never become mutation intent. Keep the original sparse
        // record and merge back only fields the typed checker actually changed.
        let original_values = std::mem::take(values);
        let owned_record = original_values.clone().into();
        match T::from_compact_row(teaql_core::CompactRow::from_map(owned_record)) {
            Ok(mut entity) => {
                let before_check = entity.clone().into_values();
                self.checker
                    .check_and_fix_typed(context, &mut entity, status, location, results);
                let after_check = entity.into_values();
                *values = original_values;
                for (field, after_value) in after_check {
                    if before_check.get(&field) != Some(&after_value) {
                        values.insert(field, after_value);
                    }
                }
            }
            Err(error) => {
                // A malformed value is not an absent required value. Preserve
                // the caller's mutation boundary and report the materialization
                // error so the offending field and actual value remain visible.
                *values = original_values;
                results.push(
                    CheckResult::new(CheckRule::InvalidType, location.clone()).with_message(
                        format!(
                            "failed to materialize {} for checker: {error}",
                            self.entity_name
                        ),
                    ),
                );
            }
        }
    }
}

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

    #[test]
    fn test_object_location_formatting_and_nesting_levels() {
        // Test root
        let root = ObjectLocation::root();
        assert_eq!(root.to_string(), "$");
        assert!(root.is_root());
        assert_eq!(root.level(), 0);

        // Test hash_root
        let hash = ObjectLocation::hash_root("user");
        assert_eq!(hash.to_string(), "user");
        assert!(!hash.is_root());
        assert_eq!(hash.level(), 1);

        // Test array_root
        let arr = ObjectLocation::array_root(5);
        assert_eq!(arr.to_string(), "[5]");
        assert!(!arr.is_root());
        assert_eq!(arr.level(), 1);

        // Test nesting
        let nested = ObjectLocation::root()
            .member("users")
            .element(2)
            .member("address")
            .member("city");

        assert_eq!(nested.to_string(), "users[2].address.city");
        assert_eq!(nested.level(), 4);
    }

    #[test]
    fn object_location_renders_model_native_and_external_paths() {
        let location = ObjectLocation::hash_root("order_items")
            .element(2)
            .member("user_url");

        assert_eq!(location.model_path(), "order_items[2].user_url");
        assert_eq!(location.native_path(), "order_items[2].user_url");
        assert_eq!(location.instance_path(), "/orderItems/2/userUrl");
        assert_eq!(location.to_string(), "order_items[2].user_url");
    }

    #[test]
    fn object_location_escapes_json_pointer_members() {
        assert_eq!(ObjectLocation::hash_root("a~/b").instance_path(), "/a~0~1b");
    }

    #[test]
    fn test_check_object_status_inference_and_explicit_markers() {
        let mut values = EntityValues::default();

        // No id -> Create
        assert_eq!(
            CheckObjectStatus::from_values(&values),
            CheckObjectStatus::Create
        );

        // Has id -> Update
        values.insert("id".to_string(), Value::I64(1));
        assert_eq!(
            CheckObjectStatus::from_values(&values),
            CheckObjectStatus::Update
        );

        // Explicit marker Create overrides id
        mark_entity_status(&mut values, CheckObjectStatus::Create);
        assert_eq!(
            CheckObjectStatus::from_values(&values),
            CheckObjectStatus::Create
        );

        // Explicit marker Update
        mark_entity_status(&mut values, CheckObjectStatus::Update);
        assert_eq!(
            CheckObjectStatus::from_values(&values),
            CheckObjectStatus::Update
        );

        // Clear marker
        clear_entity_status(&mut values);
        assert_eq!(
            CheckObjectStatus::from_values(&values),
            CheckObjectStatus::Update
        ); // falls back to id -> Update
    }
}