tablo-core 0.3.0

The core toolkit types for Tablo, a server-rendered admin toolkit on Topcoat and Toasty.
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
use toasty::schema::Model;
use topcoat::context::CxTestBuilder;

use super::*;
use crate::test_support::DummyUser;

#[test]
fn single_segment_lens_passes_traversal_is_refused() {
    use toasty::schema::Model;
    let single = toasty_core::stmt::Path::field(DummyUser::id(), 0);
    assert_eq!(single_segment(&single), Ok(0));
    let mut two = toasty_core::stmt::Path::field(DummyUser::id(), 0);
    two.chain(&toasty_core::stmt::Path::field(DummyUser::id(), 1));
    assert_eq!(
        single_segment(&two),
        Err(DeclarationErrorKind::TraversalLens { steps: 2 })
    );
}

/// Reports the lens's field name, label, and nullability.
#[test]
fn lens_field_resolves_name_label_and_nullability() {
    use toasty::schema::Model;
    let model = DummyUser::schema();

    let email = lens_field(DummyUser::fields().email(), &model).unwrap();
    assert_eq!(email.name.app_unwrap(), "email");
    assert_eq!(lens_label(&email), "Email");
    assert!(!email.nullable());
    assert_eq!(email.name.storage_name(), Some("email"));

    let name = lens_field(DummyUser::fields().name(), &model).unwrap();
    assert_eq!(name.name.app_unwrap(), "name");
    assert_eq!(lens_label(&name), "Name");
}

/// Reports uniqueness from the model's index list, where `#[unique]` lives.
#[test]
fn lens_field_unique_reads_the_model_index_list() {
    use toasty::schema::Model;
    let model = DummyUser::schema();
    let root = model.as_root_unwrap();

    let email = lens_field(DummyUser::fields().email(), &model).unwrap();
    assert!(
        lens_field_unique(&email, root),
        "#[unique] on email must surface as a single-field unique index"
    );

    let name = lens_field(DummyUser::fields().name(), &model).unwrap();
    assert!(
        !lens_field_unique(&name, root),
        "a field with no unique index must not report unique"
    );

    let id = lens_field(DummyUser::fields().id(), &model).unwrap();
    assert!(
        !lens_field_unique(&id, root),
        "the primary key is unique by construction, not by declared constraint"
    );
}

// `FieldResolver` reads the compiled schema the request carries, so these tests build a `Db` over
// one model carrying every shape the resolver reads.

/// An embedded struct: its leaves flatten into the parent's table.
#[derive(Debug, Clone, toasty::Embed)]
struct Seo {
    title: String,
    description: String,
}

/// The deepest level of `media_poster_credit_author`.
#[derive(Debug, Clone, toasty::Embed)]
struct Credit {
    author: String,
}

#[derive(Debug, Clone, toasty::Embed)]
struct Poster {
    url: String,
    credit: Credit,
}

/// An embedded enum with a struct nested inside a variant: the path
/// `media().video().poster().credit().author()` is three levels deep and
/// still lands on one flat column.
#[derive(Debug, Clone, toasty::Embed)]
enum Media {
    #[column(variant = 1)]
    Image { url: String, alt: String },
    #[column(variant = 2)]
    Video { video_url: String, poster: Poster },
}

/// Two variants declaring one `#[shared(timestamp)]` column.
#[derive(Debug, Clone, toasty::Embed)]
enum Publication {
    #[column(variant = 1)]
    Scheduled {
        #[shared(timestamp)]
        scheduled_at: String,
        scheduled_for: String,
    },
    #[column(variant = 2)]
    Published {
        #[shared(timestamp)]
        published_at: String,
        canonical_url: String,
    },
}

/// A struct holding an enum: the nested discriminant is a key of the value
/// too, not only its payloads.
#[derive(Debug, Clone, toasty::Embed)]
struct Wrapper {
    label: String,
    inner: Media,
}

/// A `#[document]`: a primitive whose storage is a model, so its inner
/// fields share one column named after the field.
#[derive(Debug, Clone, toasty::Embed)]
struct Stats {
    word_count: i64,
    read_minutes: i64,
}

#[derive(Debug, Clone, toasty::Model)]
struct LensPost {
    #[key]
    #[auto]
    id: uuid::Uuid,
    title: String,
    seo: Seo,
    media: Media,
    publication: Publication,
    wrapper: Wrapper,
    #[document]
    stats: Stats,
}

/// A second root model, embedding what `LensPost` embeds.
#[derive(Debug, Clone, toasty::Model)]
struct Impostor {
    #[key]
    #[auto]
    id: uuid::Uuid,
    seo: Seo,
    wrapper: Wrapper,
}

/// The request context a resolver reads its schema from.
async fn cx_with(models: toasty::schema::ModelSet) -> Cx {
    let db = toasty::Db::builder()
        .models(models)
        .connect("sqlite::memory:")
        .await
        .expect("connect");
    CxTestBuilder::new().app_context(db).build()
}

/// The context `LensPost`'s lenses resolve against.
async fn lens_cx() -> Cx {
    cx_with(toasty::models!(LensPost)).await
}

/// A plain leaf: a single segment on a model root never enters the walk, so
/// the owned app field answers name, label and nullability.
#[tokio::test]
async fn a_plain_leaf_resolves_through_the_app_field() {
    let cx = lens_cx().await;
    let leaf = FieldResolver::new(schema_of(&cx))
        .resolve(LensPost::fields().title())
        .unwrap();
    assert_eq!(leaf.name, "title");
    assert_eq!(leaf.label, "Title");
    assert!(
        !leaf.nullable,
        "a required top-level column is not storage-nullable"
    );
}

/// Resolves one embedded step to its flattened column.
#[tokio::test]
async fn a_leaf_in_an_embedded_struct_resolves_to_its_flattened_column() {
    let cx = lens_cx().await;
    let leaf = FieldResolver::new(schema_of(&cx))
        .resolve(LensPost::fields().seo().title())
        .unwrap();
    assert_eq!(leaf.name, "seo_title");
    assert_eq!(
        leaf.label, "Seo title",
        "a label reads the storage name as prose"
    );
    assert!(
        leaf.nullable,
        "an embedded leaf is never required by default"
    );
}

/// Resolves a variant-rooted path through nested structs to one flat column.
#[tokio::test]
async fn a_leaf_in_a_struct_nested_in_an_enum_variant_resolves_to_one_column() {
    let cx = lens_cx().await;
    let resolver = FieldResolver::new(schema_of(&cx));

    // media.image().url() — the other variant, one level down.
    assert_eq!(
        resolver
            .resolve(LensPost::fields().media().image().url())
            .unwrap()
            .name,
        "media_url"
    );
    // media.video().poster().url() — a struct one level inside the variant.
    assert_eq!(
        resolver
            .resolve(LensPost::fields().media().video().poster().url())
            .unwrap()
            .name,
        "media_poster_url"
    );
    // media.video().poster().credit().author() — three levels, one column.
    let leaf = resolver
        .resolve(
            LensPost::fields()
                .media()
                .video()
                .poster()
                .credit()
                .author(),
        )
        .unwrap();
    assert_eq!(leaf.name, "media_poster_credit_author");
    assert_eq!(leaf.label, "Media poster credit author");
    assert!(leaf.nullable);
}

/// Resolves a variant-rooted path through an embedded struct.
#[tokio::test]
async fn a_variant_rooted_path_through_an_embedded_struct_resolves() {
    let cx = lens_cx().await;
    let resolver = FieldResolver::new(schema_of(&cx));
    assert_eq!(
        resolver
            .resolve(LensPost::fields().wrapper().inner().image().url())
            .unwrap()
            .name,
        "wrapper_inner_url"
    );
    assert_eq!(
        resolver
            .resolve(LensPost::fields().wrapper().inner().video().video_url())
            .unwrap()
            .name,
        "wrapper_inner_video_url"
    );
}

/// Resolves a shared column for every variant that declares it.
#[tokio::test]
async fn a_shared_column_resolves_for_every_variant_that_declares_it() {
    let cx = lens_cx().await;
    let resolver = FieldResolver::new(schema_of(&cx));
    assert_eq!(
        resolver
            .resolve(LensPost::fields().publication().scheduled().scheduled_at())
            .unwrap()
            .name,
        "publication_timestamp"
    );
    assert_eq!(
        resolver
            .resolve(LensPost::fields().publication().published().published_at())
            .unwrap()
            .name,
        "publication_timestamp"
    );
    assert_eq!(
        resolver
            .resolve(LensPost::fields().publication().published().canonical_url())
            .unwrap()
            .name,
        "publication_canonical_url"
    );
}

/// Resolves a document leaf to the document column.
#[tokio::test]
async fn a_document_leaf_resolves_to_the_document_column() {
    let cx = lens_cx().await;
    let leaf = FieldResolver::new(schema_of(&cx))
        .resolve(LensPost::fields().stats().word_count())
        .unwrap();
    assert_eq!(leaf.name, "stats");
    assert_eq!(leaf.label, "Stats");
    assert!(
        leaf.nullable,
        "a document leaf is never required by default either"
    );
}

/// Resolves to nothing when the schema does not carry the lens's root model.
#[tokio::test]
async fn a_root_model_the_schema_does_not_carry_resolves_to_nothing() {
    let cx = cx_with(toasty::models!(Impostor)).await;
    let resolver = FieldResolver::new(schema_of(&cx));
    assert!(resolver.has_schema(), "the Db carries the app schema");
    assert!(
        schema_of(&cx)
            .expect("the Db carries the app schema")
            .app
            .get_model(<LensPost as Model>::id())
            .is_none(),
        "this schema carries no model under the lens's id"
    );
    assert!(
        resolver
            .resolve_enum(LensPost::fields().publication().into())
            .is_none(),
        "an enum cannot resolve against a schema that has no LensPost"
    );
}

/// Refuses a leaf lens the schema does not carry.
#[tokio::test]
async fn a_root_model_the_schema_does_not_carry_refuses_a_leaf_lens() {
    let cx = cx_with(toasty::models!(Impostor)).await;
    let error = FieldResolver::new(schema_of(&cx))
        .resolve(LensPost::fields().seo().title())
        .expect_err("a lens the schema cannot bind is refused");
    assert!(
        matches!(error, DeclarationErrorKind::UnresolvedLens { .. }),
        "{error}"
    );
}

/// Resolves an embedded enum's discriminant and variants in declaration order.
#[tokio::test]
async fn an_embedded_enum_resolves_its_discriminant_and_variants() {
    let cx = lens_cx().await;
    let shape = FieldResolver::new(schema_of(&cx))
        .resolve_enum(LensPost::fields().publication().into())
        .expect("an embedded enum resolves");
    assert_eq!(shape.discriminant, "publication");
    assert_eq!(
        shape.variants,
        [
            ("1".to_string(), "Scheduled".to_string()),
            ("2".to_string(), "Published".to_string()),
        ]
    );
}

/// Resolves an enum nested in a struct through the struct's path.
#[tokio::test]
async fn an_enum_inside_a_struct_resolves_through_its_path() {
    let cx = lens_cx().await;
    let shape = FieldResolver::new(schema_of(&cx))
        .resolve_enum(LensPost::fields().wrapper().inner().into())
        .expect("the nested enum resolves");
    assert_eq!(shape.discriminant, "wrapper_inner");
}

/// Resolves anything but an enum to nothing.
#[tokio::test]
async fn anything_but_an_enum_resolves_to_nothing() {
    let cx = lens_cx().await;
    let resolver = FieldResolver::new(schema_of(&cx));
    assert!(
        resolver
            .resolve_enum(LensPost::fields().seo().into())
            .is_none(),
        "a struct has no variant"
    );
    assert!(
        resolver.resolve_enum(LensPost::fields().title()).is_none(),
        "a primitive field is a leaf"
    );
    assert!(
        resolver
            .resolve_enum(LensPost::fields().stats().into())
            .is_none(),
        "a #[document] stores as one column"
    );
    assert!(
        resolver
            .resolve_enum(LensPost::fields().media().video().video_url())
            .is_none(),
        "a variant-rooted path names one variant, not the value"
    );
}

/// Resolves to nothing without a schema.
#[test]
fn without_a_schema_there_is_no_walk() {
    let cx = CxTestBuilder::new().build();
    let resolver = FieldResolver::new(schema_of(&cx));
    assert!(!resolver.has_schema(), "a bare Cx carries no Db");
    assert!(
        resolver
            .resolve_enum(LensPost::fields().publication().into())
            .is_none(),
        "an enum needs the app schema"
    );
}