rango-store 0.1.0

Typed, transaction-safe storage for Rango over SQLite and PostgreSQL
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
use std::sync::Arc;

use crate::{BoxFuture, Gather, Reader, Show, Storable, Store, StoreError, Value, Widget, Writer};

/// A table name.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Table(pub &'static str);

/// A column name.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Name(pub &'static str);

impl Table {
    /// The underlying `&'static str`.
    pub fn as_str(&self) -> &'static str {
        self.0
    }
}

impl Name {
    /// The underlying `&'static str`.
    pub fn as_str(&self) -> &'static str {
        self.0
    }
}

impl std::fmt::Display for Table {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.0)
    }
}

impl std::fmt::Display for Name {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.0)
    }
}

/// A fixed set of (value, label) choices for a field.
#[derive(Clone, Debug, PartialEq)]
pub struct Pick {
    /// Allowed choices; first element is the stored value.
    pub options: &'static [(&'static str, &'static str)],
}

/// A named checkbox constraint.
#[derive(Clone, Debug, PartialEq)]
pub struct Check(pub &'static str);

/// Reference between tables.
#[derive(Clone, Debug, PartialEq)]
pub enum Link {
    /// Direct reference to a column of another table.
    To(Table, Name),
    /// Many-to-many through a join table: table, our column, their column.
    Via(Table, Name, Name),
}

/// Repository-level constraint attached to a [`Schema`].
#[derive(Clone, Debug, PartialEq)]
pub enum Rule {
    /// The named columns must hold equal values across related rows.
    Same(Vec<Name>),
    /// The named column keeps a reference shared by linked rows.
    Hold(Name),
    /// A named checkbox constraint must hold.
    Said(Check),
}

/// Comparison operator for a [`Filter`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Op {
    /// Equal.
    Eq,
    /// Not equal.
    Ne,
    /// Strictly greater.
    More,
    /// Strictly less.
    Less,
    /// Within the given calendar day.
    At,
    /// Case-insensitive SQL `LIKE` match.
    Like,
    /// `IS NULL` on the field.
    Bare,
}

/// A leaf condition on one field.
#[derive(Clone, Debug, PartialEq)]
pub struct Filter {
    /// Field to compare.
    pub field: Name,
    /// Comparison operator.
    pub op: Op,
    /// Comparison value.
    pub value: Value,
}

/// Nested query condition.
#[derive(Clone, Debug, PartialEq)]
pub enum Tree {
    /// A single leaf filter.
    Leaf(Filter),
    /// All branches must hold.
    And(Vec<Tree>),
    /// At least one branch must hold.
    Or(Vec<Tree>),
    /// Negation of the wrapped branch.
    Cut(Box<Tree>),
}

/// Sort direction.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Order {
    /// Ascending.
    Asc,
    /// Descending.
    Desc,
}

/// A sort on one field.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Sort {
    /// Field to sort by.
    pub field: Name,
    /// Sort direction.
    pub order: Order,
}

impl Sort {
    /// Parses `-name`/`name` into a [`Sort`]; unknown fields fall back to the schema key.
    pub fn parse(raw: &str, schema: &Schema) -> Self {
        let (name, order) = match raw.strip_prefix('-') {
            Some(name) => (name, Order::Desc),
            None => (raw, Order::Asc),
        };
        let known = schema
            .fields
            .iter()
            .any(|field| field.name.as_str() == name);
        if known {
            for field in &schema.fields {
                if field.name.as_str() == name {
                    return Sort {
                        field: field.name,
                        order,
                    };
                }
            }
        }
        Sort {
            field: schema.key(),
            order: Order::Asc,
        }
    }
}

/// Paging window; `count` 0 means no limit.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Page {
    /// Maximum rows, 0 for all.
    pub count: usize,
    /// Rows to skip.
    pub offset: usize,
}

impl Page {
    /// The full page: no limit, no offset.
    pub fn all() -> Self {
        Self {
            count: 0,
            offset: 0,
        }
    }
}

/// Which columns a query returns.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Only {
    /// Every physical column.
    All,
    /// Only the named columns.
    Some(Vec<Name>),
    /// First matching row, all columns.
    Lone,
}

/// Aggregate over matching rows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mass {
    /// Row count.
    Count,
    /// Sum of a column.
    Sum(Name),
    /// Average of a column.
    Mean(Name),
    /// Minimum of a column.
    Low(Name),
    /// Maximum of a column.
    High(Name),
}

/// A full read: condition, sort, page, columns, optional aggregate.
#[derive(Clone, Debug, PartialEq)]
pub struct Query {
    /// Root condition.
    pub tree: Tree,
    /// Ordering.
    pub sort: Vec<Sort>,
    /// Paging window.
    pub page: Page,
    /// Columns to return.
    pub only: Only,
    /// Optional aggregate.
    pub mass: Option<Mass>,
}

/// A row key: autoincrement id or text key.
#[derive(Clone, Debug, PartialEq)]
pub enum Key {
    /// Autoincrement `id` key.
    Int(i64),
    /// Custom text key.
    Text(String),
}

impl Key {
    /// Converts a [`Value`] into a key, or [`StoreError::Value`].
    pub fn of(value: &Value) -> Result<Self, StoreError> {
        match value {
            Value::Int(id) => Ok(Key::Int(*id)),
            Value::Str(text) => Ok(Key::Text(text.clone())),
            _ => Err(StoreError::Value("bad key".into())),
        }
    }

    /// Parses raw text into a key: text when the schema is keyed, else int-or-text.
    pub fn parse(raw: &str, schema: &Schema) -> Self {
        let keyed = schema
            .fields
            .iter()
            .any(|field| field.keyed && !field.id && field.name == schema.key());
        if keyed {
            return Key::Text(raw.into());
        }
        match raw.parse::<i64>() {
            Ok(id) => Key::Int(id),
            Err(_) => Key::Text(raw.into()),
        }
    }

    /// This key as a [`Value`].
    pub fn value(&self) -> Value {
        match self {
            Key::Int(id) => Value::int(*id),
            Key::Text(text) => Value::str(text),
        }
    }
}

/// Spec for one column of a schema.
#[derive(Clone)]
pub struct Field {
    /// Column name.
    pub name: Name,
    /// SQL type name (`INTEGER`, `REAL`, or `TEXT`).
    pub dtype: &'static str,
    /// Autoincrement primary key column.
    pub id: bool,
    /// Primary key with a caller-supplied value.
    pub keyed: bool,
    /// Virtual many-to-many column, not stored inline.
    pub many: bool,
    /// Nullable column.
    pub optional: bool,
    /// Unique constraint.
    pub unique: bool,
    /// Indexed column.
    pub index: bool,
    /// Fixed choice list, if any.
    pub pick: Option<Pick>,
    /// Default value factory, if any.
    pub default: Option<DefaultFn>,
    /// Reference to another table, if any.
    pub link: Option<Link>,
    /// Widget for this field.
    pub widget: fn() -> Widget,
    /// Parses raw text into the field's value.
    pub parse: fn(&str, &mut dyn Writer) -> Result<(), StoreError>,
    /// Renders the field's value as text.
    pub text: fn(&mut dyn Reader) -> String,
}

/// Default value factory writing into a [`Writer`].
pub type DefaultFn = Arc<dyn Fn(&mut dyn Writer) + Send + Sync + 'static>;

impl Field {
    /// A plain column storing any [`Storable`] + [`Show`] type.
    pub fn cell<T: Storable + Show>(name: &'static str) -> Self {
        Self {
            name: Name(name),
            dtype: T::dtype(),
            id: false,
            keyed: false,
            many: false,
            optional: false,
            unique: false,
            index: false,
            pick: None,
            default: None,
            link: None,
            widget: widget_of::<T>,
            parse: parse_of::<T>,
            text: text_of::<T>,
        }
    }

    /// An autoincrement `id` primary key column.
    pub fn id() -> Self {
        let field = Self::cell::<i64>("id");
        Self {
            id: true,
            keyed: true,
            ..field
        }
    }

    /// A caller-supplied primary key column.
    pub fn key<T: Storable + Show>(name: &'static str) -> Self {
        let field = Self::cell::<T>(name);
        Self {
            keyed: true,
            ..field
        }
    }

    /// A string column.
    pub fn str(name: &'static str) -> Self {
        Self::cell::<String>(name)
    }

    /// A boolean column.
    pub fn check(name: &'static str) -> Self {
        Self::cell::<bool>(name)
    }

    /// A virtual many-to-many column.
    pub fn many(name: &'static str) -> Self {
        Self {
            name: Name(name),
            dtype: "TEXT",
            id: false,
            keyed: false,
            many: true,
            optional: false,
            unique: false,
            index: false,
            pick: None,
            default: None,
            link: None,
            widget: nop_widget,
            parse: nop_parse,
            text: nop_text,
        }
    }

    /// Marks the column nullable.
    pub fn optional(mut self) -> Self {
        self.optional = true;
        self
    }

    /// Adds a unique constraint.
    pub fn unique(mut self) -> Self {
        self.unique = true;
        self
    }

    /// Marks the column indexed.
    pub fn indexed(mut self) -> Self {
        self.index = true;
        self
    }

    /// Sets a static default [`Storable`] value.
    pub fn default_value(mut self, value: impl Storable) -> Self {
        self.default = Some(Arc::new(move |w| value.put(w)));
        self
    }

    /// Sets a default value factory.
    pub fn default(mut self, make: impl Fn(&mut dyn Writer) + Send + Sync + 'static) -> Self {
        self.default = Some(Arc::new(make));
        self
    }

    /// Links to another table's column (`"table.column"` or just `"table"`).
    pub fn references(mut self, target: &'static str) -> Self {
        let (table, column) = match target.split_once('.') {
            Some((table, column)) => (table, column),
            None => (target, "id"),
        };
        self.link = Some(Link::To(Table(table), Name(column)));
        self
    }

    /// Sets a [`Link`] to another table.
    pub fn link(mut self, link: Link) -> Self {
        self.link = Some(link);
        self
    }

    /// The referenced (table, column) for a direct link, if any.
    pub fn reference(&self) -> Option<(Table, Name)> {
        match self.link {
            Some(Link::To(table, name)) => Some((table, name)),
            _ => None,
        }
    }

    /// The field's [`Widget`].
    pub fn load(&self) -> Widget {
        (self.widget)()
    }

    /// The field's default as a [`Value`], or [`Value::Null`].
    pub fn initial(&self) -> Value {
        match &self.default {
            Some(make) => {
                let mut gather = Gather::new();
                make(&mut gather);
                gather.value()
            }
            None => Value::Null,
        }
    }
}

fn widget_of<T: Show>() -> Widget {
    T::widget()
}

fn parse_of<T: Storable + Show>(raw: &str, w: &mut dyn Writer) -> Result<(), StoreError> {
    let value = T::parse(raw)?;
    T::put(&value, w);
    Ok(())
}

fn text_of<T: Storable + Show>(r: &mut dyn Reader) -> String {
    match T::take(r) {
        Ok(value) => T::text(&value),
        Err(_) => String::new(),
    }
}

fn nop_widget() -> Widget {
    Widget::Text
}

fn nop_parse(_raw: &str, _w: &mut dyn Writer) -> Result<(), StoreError> {
    Ok(())
}

fn nop_text(_r: &mut dyn Reader) -> String {
    String::new()
}

/// A table definition: name, fields, and rules.
#[derive(Clone)]
pub struct Schema {
    /// Table name.
    pub table: Table,
    /// Column specs.
    pub fields: Vec<Field>,
    /// Constraints.
    pub rules: Vec<Rule>,
}

impl Schema {
    /// The primary key column name.
    pub fn key(&self) -> Name {
        self.fields
            .iter()
            .find(|field| field.id || field.keyed)
            .map(|field| field.name)
            .unwrap_or(Name("id"))
    }
}

/// A bulk row action with a name, title, and handler.
#[derive(Clone, Copy, Debug)]
pub struct Action {
    /// Machine name.
    pub name: Name,
    /// Display title.
    pub title: &'static str,
    /// Handler producing a result message.
    pub run: Run,
    /// Whether the action is logged.
    pub logged: bool,
    /// Whether the action applies to selected rows.
    pub row: bool,
}

/// Action handler: store, schema, and target keys to a result message.
pub type Run =
    fn(Arc<dyn Store>, Schema, Vec<Key>) -> BoxFuture<'static, Result<String, StoreError>>;

impl Action {
    /// The built-in delete action.
    pub fn wipe() -> Self {
        Self {
            name: Name("wipe"),
            title: "Delete",
            run: wipe,
            logged: true,
            row: true,
        }
    }
}

fn wipe(
    store: Arc<dyn Store>,
    schema: Schema,
    keys: Vec<Key>,
) -> BoxFuture<'static, Result<String, StoreError>> {
    Box::pin(async move {
        for key in &keys {
            store.remove(&schema, key).await?;
        }
        if keys.len() == 1 {
            Ok("Deleted 1 row.".into())
        } else {
            Ok(format!("Deleted {} rows.", keys.len()))
        }
    })
}

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

    fn schema() -> Schema {
        Schema {
            table: Table("posts"),
            fields: vec![Field::id(), Field::str("title")],
            rules: Vec::new(),
        }
    }

    fn keyed() -> Schema {
        Schema {
            table: Table("products"),
            fields: vec![Field::key::<String>("sku"), Field::cell::<Decimal>("price")],
            rules: Vec::new(),
        }
    }

    #[test]
    fn keys() {
        assert_eq!(schema().key(), Name("id"));
        assert_eq!(keyed().key(), Name("sku"));
        assert_eq!(Key::parse("7", &schema()).value(), Value::int(7));
        assert_eq!(Key::parse("7", &keyed()).value(), Value::str("7"));
        assert_eq!(Key::parse("x", &schema()).value(), Value::str("x"));
    }

    #[test]
    fn key_of() {
        assert_eq!(Key::of(&Value::int(3)).unwrap(), Key::Int(3));
        assert_eq!(Key::of(&Value::str("x")).unwrap(), Key::Text("x".into()));
        assert!(Key::of(&Value::Null).is_err());
    }

    #[test]
    fn sorts() {
        let schema = schema();
        assert_eq!(
            Sort::parse("title", &schema),
            Sort {
                field: Name("title"),
                order: Order::Asc,
            }
        );
        assert_eq!(
            Sort::parse("-title", &schema),
            Sort {
                field: Name("title"),
                order: Order::Desc,
            }
        );
        assert_eq!(
            Sort::parse("junk", &schema),
            Sort {
                field: Name("id"),
                order: Order::Asc,
            }
        );
    }
}