kyyn-core 0.1.10

Core vocabulary for kyyn: registry, links, query AST, plugin and validation contracts for typed, git-backed knowledge bases.
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
//! Backend-neutral analytical query plans and the typed builder schemas use
//! to produce them. The builder closure runs once against typed field proxies;
//! only the resulting serde AST crosses the schema/engine boundary.

use std::marker::PhantomData;

use chrono::NaiveDate;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct QueryDecl {
    pub name: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub doc: String,
    pub bindings: Vec<BindingDecl>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub filter: Option<BoolExpr>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub group_by: Vec<ScalarExpr>,
    pub columns: Vec<OutputColumn>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub order_by: Vec<QueryOrder>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BindingDecl {
    pub id: u32,
    pub kind: String,
    pub source: BindingSource,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BindingSource {
    Root,
    Follow {
        from: u32,
        field: String,
        direction: EdgeDirection,
        #[serde(default = "yes")]
        required: bool,
    },
}

fn yes() -> bool {
    true
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum EdgeDirection {
    Out,
    In,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FieldRef {
    pub binding: u32,
    pub field: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ScalarExpr {
    Field(FieldRef),
    Literal(TypedLiteral),
    Aggregate {
        op: AggregateOp,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        expr: Option<Box<ScalarExpr>>,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TypedLiteral {
    String(String),
    Int(i64),
    Decimal(String),
    Date(NaiveDate),
    Bool(bool),
    Enum { type_name: String, variant: String },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AggregateOp {
    Count,
    CountDistinct,
    Sum,
    Min,
    Max,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BoolExpr {
    And(Vec<BoolExpr>),
    Or(Vec<BoolExpr>),
    Not(Box<BoolExpr>),
    Compare {
        left: ScalarExpr,
        op: CompareOp,
        right: ScalarExpr,
    },
}

impl BoolExpr {
    pub fn and(self, other: BoolExpr) -> BoolExpr {
        match self {
            BoolExpr::And(mut xs) => {
                xs.push(other);
                BoolExpr::And(xs)
            }
            one => BoolExpr::And(vec![one, other]),
        }
    }

    pub fn or(self, other: BoolExpr) -> BoolExpr {
        match self {
            BoolExpr::Or(mut xs) => {
                xs.push(other);
                BoolExpr::Or(xs)
            }
            one => BoolExpr::Or(vec![one, other]),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CompareOp {
    Eq,
    Ne,
    Gt,
    Gte,
    Lt,
    Lte,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OutputColumn {
    pub name: String,
    pub expr: ScalarExpr,
    /// Display-only formatting; the underlying value stays exact and sorting
    /// uses the raw value, never the rendered text.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub format: Option<ColumnFormat>,
}

/// Declarative column formatting — serializable AST data the gate can check
/// and every face renders identically. Thousands grouping uses a SPACE
/// (29 669 069.38): the KB-wide convention.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ColumnFormat {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prefix: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub suffix: Option<String>,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub thousands: bool,
    /// Display rounding/padding only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub decimals: Option<u8>,
}

impl ColumnFormat {
    /// The money shape: prefix + space-grouped thousands + 2 decimals.
    pub fn money(prefix: impl Into<String>) -> ColumnFormat {
        ColumnFormat {
            prefix: Some(prefix.into()),
            suffix: None,
            thousands: true,
            decimals: Some(2),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct QueryOrder {
    pub expr: ScalarExpr,
    pub direction: SortDirection,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SortDirection {
    Asc,
    Desc,
}

/// A schema model that can produce a typed proxy for one query binding.
/// Implementations are normally generated alongside the registry declaration.
pub trait QueryModel: Sized {
    type Fields;
    const KIND: &'static str;
    fn fields(binding: u32) -> Self::Fields;
}

/// A typed reference to one field. `T` makes incompatible comparisons fail in
/// Rust before a plan can be emitted; serde sees only the contained FieldRef.
#[derive(Debug)]
pub struct FieldExpr<T> {
    field: FieldRef,
    marker: PhantomData<fn() -> T>,
}

impl<T> Clone for FieldExpr<T> {
    fn clone(&self) -> Self {
        Self {
            field: self.field.clone(),
            marker: PhantomData,
        }
    }
}

impl<T> FieldExpr<T> {
    pub fn new(binding: u32, field: impl Into<String>) -> Self {
        Self {
            field: FieldRef {
                binding,
                field: field.into(),
            },
            marker: PhantomData,
        }
    }

    pub fn expr(&self) -> ScalarExpr {
        ScalarExpr::Field(self.field.clone())
    }

    fn compare(&self, op: CompareOp, value: T) -> BoolExpr
    where
        T: QueryLiteral,
    {
        BoolExpr::Compare {
            left: self.expr(),
            op,
            right: ScalarExpr::Literal(value.into_query_literal()),
        }
    }

    pub fn eq(&self, value: T) -> BoolExpr
    where
        T: QueryLiteral,
    {
        self.compare(CompareOp::Eq, value)
    }

    pub fn ne(&self, value: T) -> BoolExpr
    where
        T: QueryLiteral,
    {
        self.compare(CompareOp::Ne, value)
    }

    pub fn gt(&self, value: T) -> BoolExpr
    where
        T: QueryLiteral,
    {
        self.compare(CompareOp::Gt, value)
    }

    pub fn gte(&self, value: T) -> BoolExpr
    where
        T: QueryLiteral,
    {
        self.compare(CompareOp::Gte, value)
    }

    pub fn lt(&self, value: T) -> BoolExpr
    where
        T: QueryLiteral,
    {
        self.compare(CompareOp::Lt, value)
    }

    pub fn lte(&self, value: T) -> BoolExpr
    where
        T: QueryLiteral,
    {
        self.compare(CompareOp::Lte, value)
    }

    /// The binding this field belongs to — what join builders anchor on
    /// until slice 3's typed EdgeExpr replaces the string field name.
    pub fn binding(&self) -> u32 {
        self.field.binding
    }
}

pub trait QueryLiteral {
    fn into_query_literal(self) -> TypedLiteral;
}

impl QueryLiteral for String {
    fn into_query_literal(self) -> TypedLiteral {
        TypedLiteral::String(self)
    }
}
impl QueryLiteral for &str {
    fn into_query_literal(self) -> TypedLiteral {
        TypedLiteral::String(self.to_string())
    }
}
impl QueryLiteral for i64 {
    fn into_query_literal(self) -> TypedLiteral {
        TypedLiteral::Int(self)
    }
}
impl QueryLiteral for bool {
    fn into_query_literal(self) -> TypedLiteral {
        TypedLiteral::Bool(self)
    }
}
impl QueryLiteral for NaiveDate {
    fn into_query_literal(self) -> TypedLiteral {
        TypedLiteral::Date(self)
    }
}

/// Builder used inside a schema crate. It is deliberately stateful: the
/// closure describes one plan, then `finish()` returns plain serializable data.
pub struct QueryBuilder {
    query: QueryDecl,
    next_binding: u32,
}

impl QueryBuilder {
    pub fn new(name: impl Into<String>, doc: impl Into<String>) -> Self {
        Self {
            query: QueryDecl {
                name: name.into(),
                doc: doc.into(),
                bindings: vec![],
                filter: None,
                group_by: vec![],
                columns: vec![],
                order_by: vec![],
                limit: None,
            },
            next_binding: 0,
        }
    }

    pub fn from<M: QueryModel>(&mut self) -> M::Fields {
        let id = self.next_binding;
        self.next_binding += 1;
        self.query.bindings.push(BindingDecl {
            id,
            kind: M::KIND.into(),
            source: BindingSource::Root,
        });
        M::fields(id)
    }

    pub fn filter(&mut self, expr: BoolExpr) {
        self.query.filter = Some(expr);
    }

    pub fn group_by<T>(&mut self, field: &FieldExpr<T>) {
        self.query.group_by.push(field.expr());
    }

    pub fn field<T>(&mut self, name: impl Into<String>, field: &FieldExpr<T>) -> ColumnHandle<'_> {
        self.push_column(name, field.expr())
    }

    fn push_column(&mut self, name: impl Into<String>, expr: ScalarExpr) -> ColumnHandle<'_> {
        self.query.columns.push(OutputColumn {
            name: name.into(),
            expr,
            format: None,
        });
        ColumnHandle {
            column: self.query.columns.last_mut().expect("just pushed"),
        }
    }

    pub fn count(&mut self, name: impl Into<String>) -> ColumnHandle<'_> {
        self.push_column(
            name,
            ScalarExpr::Aggregate {
                op: AggregateOp::Count,
                expr: None,
            },
        )
    }

    /// Count rows where the expression is non-null — the SQL COUNT(col)
    /// semantics; with a LEFT join this is how "0 related" stays 0.
    pub fn count_of<T>(
        &mut self,
        name: impl Into<String>,
        field: &FieldExpr<T>,
    ) -> ColumnHandle<'_> {
        self.aggregate(name, AggregateOp::Count, field)
    }

    pub fn count_distinct<T>(
        &mut self,
        name: impl Into<String>,
        field: &FieldExpr<T>,
    ) -> ColumnHandle<'_> {
        self.aggregate(name, AggregateOp::CountDistinct, field)
    }

    pub fn sum<T>(&mut self, name: impl Into<String>, field: &FieldExpr<T>) -> ColumnHandle<'_> {
        self.aggregate(name, AggregateOp::Sum, field)
    }

    pub fn min<T>(&mut self, name: impl Into<String>, field: &FieldExpr<T>) -> ColumnHandle<'_> {
        self.aggregate(name, AggregateOp::Min, field)
    }

    pub fn max<T>(&mut self, name: impl Into<String>, field: &FieldExpr<T>) -> ColumnHandle<'_> {
        self.aggregate(name, AggregateOp::Max, field)
    }

    fn aggregate<T>(
        &mut self,
        name: impl Into<String>,
        op: AggregateOp,
        field: &FieldExpr<T>,
    ) -> ColumnHandle<'_> {
        self.push_column(
            name,
            ScalarExpr::Aggregate {
                op,
                expr: Some(Box::new(field.expr())),
            },
        )
    }

    /// JOIN: bind records of `M` whose OWN link field `field` points at the
    /// `anchor` binding's record (SQL: FROM anchor JOIN M ON M.field = anchor).
    /// `required: false` is a LEFT join — anchor rows without a match keep one
    /// row with the M binding absent. The field name is a string until slice
    /// 3's typed EdgeExpr; the registry gate validates it at emission.
    pub fn follow_in<M: QueryModel>(
        &mut self,
        anchor: u32,
        field: impl Into<String>,
        required: bool,
    ) -> M::Fields {
        self.follow::<M>(anchor, field, EdgeDirection::In, required)
    }

    /// JOIN along a link field ON THE ANCHOR pointing out at records of `M`.
    pub fn follow_out<M: QueryModel>(
        &mut self,
        anchor: u32,
        field: impl Into<String>,
        required: bool,
    ) -> M::Fields {
        self.follow::<M>(anchor, field, EdgeDirection::Out, required)
    }

    fn follow<M: QueryModel>(
        &mut self,
        anchor: u32,
        field: impl Into<String>,
        direction: EdgeDirection,
        required: bool,
    ) -> M::Fields {
        let id = self.next_binding;
        self.next_binding += 1;
        self.query.bindings.push(BindingDecl {
            id,
            kind: M::KIND.into(),
            source: BindingSource::Follow {
                from: anchor,
                field: field.into(),
                direction,
                required,
            },
        });
        M::fields(id)
    }

    pub fn order_by<T>(&mut self, field: &FieldExpr<T>, direction: SortDirection) {
        self.query.order_by.push(QueryOrder {
            expr: field.expr(),
            direction,
        });
    }

    /// Order by an output column's expression (aggregates included).
    pub fn order_by_column(&mut self, name: &str, direction: SortDirection) {
        if let Some(col) = self.query.columns.iter().find(|c| c.name == name) {
            self.query.order_by.push(QueryOrder {
                expr: col.expr.clone(),
                direction,
            });
        }
    }

    pub fn limit(&mut self, limit: usize) {
        self.query.limit = Some(limit);
    }

    pub fn finish(self) -> QueryDecl {
        self.query
    }
}

/// Fluent formatting on the just-declared column:
/// `q.sum("total budget", &f).money("R ")`.
pub struct ColumnHandle<'a> {
    column: &'a mut OutputColumn,
}

impl ColumnHandle<'_> {
    pub fn format(self, format: ColumnFormat) -> Self {
        self.column.format = Some(format);
        self
    }

    pub fn money(self, prefix: impl Into<String>) -> Self {
        self.format(ColumnFormat::money(prefix))
    }
}

pub fn query(
    name: impl Into<String>,
    doc: impl Into<String>,
    build: impl FnOnce(&mut QueryBuilder),
) -> QueryDecl {
    let mut q = QueryBuilder::new(name, doc);
    build(&mut q);
    q.finish()
}