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
use serde_yaml::Value;

use crate::model::Key;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OperationKind {
    Find,
    Count,
    Update,
    Delete,
}

#[derive(Debug, Clone, PartialEq)]
pub enum Operation {
    Find(FindOp),
    Count(CountOp),
    Update(UpdateOp),
    Delete(DeleteOp),
}

#[derive(Debug, Clone, Default, PartialEq)]
pub struct FindOp {
    pub filter: Option<Filter>,
    pub project: Option<Projection>,
    pub sort: Option<Sort>,
    pub limit: Option<Limit>,
}

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

    pub fn filter(mut self, filter: Filter) -> Self {
        self.filter = Some(filter);
        self
    }

    pub fn project(mut self, project: Projection) -> Self {
        self.project = Some(project);
        self
    }

    pub fn sort(mut self, sort: Sort) -> Self {
        self.sort = Some(sort);
        self
    }

    pub fn limit(mut self, limit: u64) -> Self {
        self.limit = Some(Limit(limit));
        self
    }
}

#[derive(Debug, Clone, Default, PartialEq)]
pub struct CountOp {
    pub filter: Option<Filter>,
    pub sort: Option<Sort>,
    pub limit: Option<Limit>,
}

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

    pub fn filter(mut self, filter: Filter) -> Self {
        self.filter = Some(filter);
        self
    }

    pub fn sort(mut self, sort: Sort) -> Self {
        self.sort = Some(sort);
        self
    }

    pub fn limit(mut self, limit: u64) -> Self {
        self.limit = Some(Limit(limit));
        self
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct UpdateOp {
    pub filter: Filter,
    pub sort: Option<Sort>,
    pub limit: Option<Limit>,
    pub update: Update,
}

impl UpdateOp {
    pub fn new(filter: Filter, update: Update) -> Self {
        Self {
            filter,
            sort: None,
            limit: None,
            update,
        }
    }

    pub fn sort(mut self, sort: Sort) -> Self {
        self.sort = Some(sort);
        self
    }

    pub fn limit(mut self, limit: u64) -> Self {
        self.limit = Some(Limit(limit));
        self
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct DeleteOp {
    pub filter: Filter,
    pub sort: Option<Sort>,
    pub limit: Option<Limit>,
}

impl DeleteOp {
    pub fn new(filter: Filter) -> Self {
        Self {
            filter,
            sort: None,
            limit: None,
        }
    }

    pub fn sort(mut self, sort: Sort) -> Self {
        self.sort = Some(sort);
        self
    }

    pub fn limit(mut self, limit: u64) -> Self {
        self.limit = Some(Limit(limit));
        self
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum Filter {
    And(Vec<Filter>),
    Or(Vec<Filter>),
    Nor(Vec<Filter>),
    Field { path: FieldPath, op: FieldOp },
    Key(KeyOp),
    Includes(Box<InclusionAnchor>),
    IncludedBy(Box<InclusionAnchor>),
    References(Box<ReferenceAnchor>),
    ReferencedBy(Box<ReferenceAnchor>),
}

#[derive(Debug, Clone, PartialEq)]
pub enum KeyOp {
    Eq(Key),
    Ne(Key),
    In(Vec<Key>),
    Nin(Vec<Key>),
}

impl KeyOp {
    pub fn eq(key: impl Into<String>) -> Self {
        KeyOp::Eq(Key::name(&key.into()))
    }
    pub fn ne(key: impl Into<String>) -> Self {
        KeyOp::Ne(Key::name(&key.into()))
    }
    pub fn in_(keys: &[&str]) -> Self {
        KeyOp::In(keys.iter().map(|s| Key::name(s)).collect())
    }
    pub fn nin(keys: &[&str]) -> Self {
        KeyOp::Nin(keys.iter().map(|s| Key::name(s)).collect())
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct InclusionAnchor {
    pub match_filter: Filter,
    pub min_depth: u32,
    pub max_depth: u32,
}

impl InclusionAnchor {
    pub fn new(key: impl Into<String>, min_depth: u32, max_depth: u32) -> Self {
        InclusionAnchor {
            match_filter: Filter::Key(KeyOp::Eq(Key::name(&key.into()))),
            min_depth,
            max_depth,
        }
    }
    pub fn with_max(key: impl Into<String>, max_depth: u32) -> Self {
        Self::new(key, 1, max_depth)
    }
    pub fn with_match(match_filter: Filter, min_depth: u32, max_depth: u32) -> Self {
        InclusionAnchor {
            match_filter,
            min_depth,
            max_depth,
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct ReferenceAnchor {
    pub match_filter: Filter,
    pub min_distance: u32,
    pub max_distance: u32,
}

impl ReferenceAnchor {
    pub fn new(key: impl Into<String>, min_distance: u32, max_distance: u32) -> Self {
        ReferenceAnchor {
            match_filter: Filter::Key(KeyOp::Eq(Key::name(&key.into()))),
            min_distance,
            max_distance,
        }
    }
    pub fn with_max(key: impl Into<String>, max_distance: u32) -> Self {
        Self::new(key, 1, max_distance)
    }
    pub fn with_match(match_filter: Filter, min_distance: u32, max_distance: u32) -> Self {
        ReferenceAnchor {
            match_filter,
            min_distance,
            max_distance,
        }
    }
}

impl Filter {
    pub fn all() -> Self {
        Filter::And(Vec::new())
    }

    pub fn and(filters: Vec<Filter>) -> Self {
        Filter::And(filters)
    }

    pub fn or(filters: Vec<Filter>) -> Self {
        Filter::Or(filters)
    }

    pub fn eq(path: &str, v: impl Into<Value>) -> Self {
        Self::field(path, FieldOp::Eq(v.into()))
    }

    pub fn ne(path: &str, v: impl Into<Value>) -> Self {
        Self::field(path, FieldOp::Ne(v.into()))
    }

    pub fn gt(path: &str, v: impl Into<Value>) -> Self {
        Self::field(path, FieldOp::Gt(v.into()))
    }

    pub fn gte(path: &str, v: impl Into<Value>) -> Self {
        Self::field(path, FieldOp::Gte(v.into()))
    }

    pub fn lt(path: &str, v: impl Into<Value>) -> Self {
        Self::field(path, FieldOp::Lt(v.into()))
    }

    pub fn lte(path: &str, v: impl Into<Value>) -> Self {
        Self::field(path, FieldOp::Lte(v.into()))
    }

    pub fn exists(path: &str, present: bool) -> Self {
        Self::field(path, FieldOp::Exists(present))
    }

    pub fn key(op: KeyOp) -> Self {
        Filter::Key(op)
    }

    fn field(path: &str, op: FieldOp) -> Self {
        Filter::Field {
            path: FieldPath::from_dotted(path),
            op,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FieldPath(pub Vec<String>);

impl FieldPath {
    pub fn segments(&self) -> &[String] {
        &self.0
    }

    pub fn from_dotted(s: &str) -> Self {
        FieldPath(s.split('.').map(|seg| seg.to_string()).collect())
    }

    pub fn leaf(&self) -> Option<&str> {
        self.0.last().map(|s| s.as_str())
    }

    pub fn starts_with(&self, other: &FieldPath) -> bool {
        if other.0.len() > self.0.len() {
            return false;
        }
        self.0.iter().zip(other.0.iter()).all(|(a, b)| a == b)
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum FieldOp {
    Eq(Value),
    Ne(Value),
    Gt(Value),
    Gte(Value),
    Lt(Value),
    Lte(Value),
    In(Vec<Value>),
    Nin(Vec<Value>),
    Exists(bool),
    Type(Vec<YamlType>),
    All(Vec<Value>),
    Size(u64),
    Not(Box<FieldOp>),
    And(Vec<FieldOp>),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum YamlType {
    String,
    Number,
    Boolean,
    Null,
    Array,
    Object,
    Date,
    Datetime,
}

impl std::fmt::Display for YamlType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            YamlType::String => write!(f, "string"),
            YamlType::Number => write!(f, "number"),
            YamlType::Boolean => write!(f, "boolean"),
            YamlType::Null => write!(f, "null"),
            YamlType::Array => write!(f, "array"),
            YamlType::Object => write!(f, "object"),
            YamlType::Date => write!(f, "date"),
            YamlType::Datetime => write!(f, "datetime"),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProjectionMode {
    Replace,
    Extend,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PseudoField {
    Key,
    Title,
    TitleSlug,
    Content,
    Frontmatter,
    IncludedBy,
    Includes,
    ReferencedBy,
    References,
}

impl PseudoField {
    pub fn from_selector(s: &str) -> Option<Self> {
        match s {
            "$key" => Some(PseudoField::Key),
            "$title" => Some(PseudoField::Title),
            "$titleSlug" => Some(PseudoField::TitleSlug),
            "$content" => Some(PseudoField::Content),
            "$frontmatter" => Some(PseudoField::Frontmatter),
            "$includedBy" => Some(PseudoField::IncludedBy),
            "$includes" => Some(PseudoField::Includes),
            "$referencedBy" => Some(PseudoField::ReferencedBy),
            "$references" => Some(PseudoField::References),
            _ => None,
        }
    }

    pub fn default_output_name(&self) -> &'static str {
        match self {
            PseudoField::Key => "key",
            PseudoField::Title => "title",
            PseudoField::TitleSlug => "titleSlug",
            PseudoField::Content => "content",
            PseudoField::Frontmatter => "frontmatter",
            PseudoField::IncludedBy => "includedBy",
            PseudoField::Includes => "includes",
            PseudoField::ReferencedBy => "referencedBy",
            PseudoField::References => "references",
        }
    }

    pub fn is_content_or_edge(&self) -> bool {
        matches!(
            self,
            PseudoField::Content
                | PseudoField::IncludedBy
                | PseudoField::Includes
                | PseudoField::ReferencedBy
                | PseudoField::References
        )
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum ProjectionSource {
    Frontmatter(FieldPath),
    Pseudo(PseudoField),
}

#[derive(Debug, Clone, PartialEq)]
pub struct ProjectionField {
    pub output: String,
    pub source: ProjectionSource,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Projection {
    pub fields: Vec<ProjectionField>,
    pub mode: ProjectionMode,
}

impl Projection {
    pub fn replace(fields: Vec<ProjectionField>) -> Self {
        Projection {
            fields,
            mode: ProjectionMode::Replace,
        }
    }

    pub fn extend(fields: Vec<ProjectionField>) -> Self {
        Projection {
            fields,
            mode: ProjectionMode::Extend,
        }
    }

    pub fn fields(fields: &[&str]) -> Self {
        Projection {
            fields: fields
                .iter()
                .map(|name| ProjectionField {
                    output: (*name).to_string(),
                    source: ProjectionSource::Frontmatter(FieldPath::from_dotted(name)),
                })
                .collect(),
            mode: ProjectionMode::Replace,
        }
    }

    pub fn default_for_find() -> Self {
        let entries = [
            ("key", PseudoField::Key),
            ("title", PseudoField::Title),
            ("references", PseudoField::References),
            ("includes", PseudoField::Includes),
            ("referencedBy", PseudoField::ReferencedBy),
            ("includedBy", PseudoField::IncludedBy),
        ];
        Projection {
            fields: entries
                .iter()
                .map(|(name, p)| ProjectionField {
                    output: (*name).to_string(),
                    source: ProjectionSource::Pseudo(*p),
                })
                .collect(),
            mode: ProjectionMode::Replace,
        }
    }

    pub fn has_content_or_edge_source(&self) -> bool {
        self.fields.iter().any(|f| match &f.source {
            ProjectionSource::Pseudo(p) => p.is_content_or_edge(),
            _ => false,
        })
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Sort {
    pub key: FieldPath,
    pub dir: SortDir,
}

impl Sort {
    pub fn asc(path: &str) -> Self {
        Sort {
            key: FieldPath::from_dotted(path),
            dir: SortDir::Asc,
        }
    }

    pub fn desc(path: &str) -> Self {
        Sort {
            key: FieldPath::from_dotted(path),
            dir: SortDir::Desc,
        }
    }
}

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

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Limit(pub u64);

impl Limit {
    pub fn is_unbounded(self) -> bool {
        self.0 == 0
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Update {
    pub operators: Vec<UpdateOperator>,
}

impl Update {
    pub fn new(operators: Vec<UpdateOperator>) -> Self {
        Update { operators }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum UpdateOperator {
    Set { path: FieldPath, value: Value },
    Unset { path: FieldPath },
}

impl UpdateOperator {
    pub fn set(path: &str, value: impl Into<Value>) -> Self {
        UpdateOperator::Set {
            path: FieldPath::from_dotted(path),
            value: value.into(),
        }
    }

    pub fn unset(path: &str) -> Self {
        UpdateOperator::Unset {
            path: FieldPath::from_dotted(path),
        }
    }
}