glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
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
//! Active Record-style records: build, change and save in place, with
//! errors and dirty tracking on the record. Runs on SQLite, and on Postgres
//! when `GLACIER_TEST_POSTGRES_URL` is set.

use glacier::db::migration::{Migration, Schema};
use glacier::db::{self, Repo, Value};
use glacier::prelude::*;

#[glacier::model]
pub struct Post {
    #[validate(required)]
    title: String,
    #[validate(unique)]
    slug: String,
    body: Option<String>,
    views: i32,
    status: Status,
}

#[glacier::enumeration]
pub enum Status {
    Draft,
    Published,
    InReview,
}

#[glacier::scopes]
impl Post {
    /// Posts with ten or more views.
    fn popular(posts: Query<Self>) -> Query<Self> {
        posts.filter(|p| p.views.ge(10))
    }

    fn titled(posts: Query<Post>, prefix: &str) -> Query<Post> {
        let pattern = format!("{prefix}%");
        posts.filter(|p| p.title.like(pattern))
    }
}

/// Records the callbacks it runs, in order.
#[glacier::model(callbacks)]
pub struct Article {
    #[validate(required)]
    title: String,
    slug: String,
    #[glacier(skip)]
    ran: Vec<&'static str>,
}

impl Callbacks for Article {
    async fn before_validation(&mut self) -> glacier::Result<()> {
        self.ran.push("before_validation");
        if self.title == "fail" {
            return Err(Error::internal("refused"));
        }
        Ok(())
    }
    async fn before_save(&mut self) -> glacier::Result<()> {
        self.ran.push("before_save");
        self.slug = self.title.to_lowercase().replace(' ', "-");
        Ok(())
    }
    async fn before_create(&mut self) -> glacier::Result<()> {
        self.ran.push("before_create");
        Ok(())
    }
    async fn before_update(&mut self) -> glacier::Result<()> {
        self.ran.push("before_update");
        Ok(())
    }
    // After the write the record is fresh from the database, so these
    // see an empty `ran`.
    async fn after_save(&mut self) -> glacier::Result<()> {
        self.ran.push("after_save");
        Ok(())
    }
    async fn before_destroy(&mut self) -> glacier::Result<()> {
        DESTROYED.store(self.id, std::sync::atomic::Ordering::SeqCst);
        Ok(())
    }
}

static DESTROYED: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(0);

fn schema(s: &mut Schema) {
    s.create_table("posts", |t| {
        t.string("title").not_null();
        t.string("slug").not_null().unique();
        t.text("body");
        t.integer("views").not_null().default(0);
        t.string("status").not_null().default("draft");
        t.timestamps();
    });
    s.create_table("articles", |t| {
        t.string("title").not_null();
        t.string("slug").not_null();
        t.timestamps();
    });
    s.create_table("accounts", |t| {
        t.string("email").not_null();
        t.string("password_digest").not_null();
        t.timestamps();
    });
}

/// A password, kept only as a digest: the callback clears it once hashed.
#[glacier::model(callbacks)]
pub struct Account {
    email: String,
    password_digest: String,
    #[glacier(attribute)]
    password: Option<String>,
}

impl glacier::Callbacks for Account {
    fn validate_record(&self, errors: &mut glacier::db::Errors) {
        if self.password_digest.is_empty() && self.password.as_deref().unwrap_or("").len() < 8 {
            errors.add("password", "is too short (minimum is 8 characters)");
        }
    }

    async fn before_save(&mut self) -> glacier::Result<()> {
        if let Some(password) = self.password.take() {
            self.password_digest = format!("hashed:{password}");
        }
        Ok(())
    }
}

macro_rules! each_db {
    (|$repo:ident| $body:expr) => {{
        let mut urls = vec!["sqlite::memory:".to_owned()];
        if let Ok(url) = std::env::var("GLACIER_TEST_POSTGRES_URL") {
            urls.push(url);
        }
        for url in urls {
            let $repo = Repo::connect(&url).await.unwrap();
            db::sandbox(&$repo, async {
                for statement in Migration::new("m1_posts", schema, |_| {}).up_sql($repo.dialect())
                {
                    db::sql(&statement).execute().await.unwrap();
                }
                $body
            })
            .await
            .unwrap();
        }
    }};
}

fn params(pairs: &[(&str, &str)]) -> Params {
    pairs.iter().copied().collect()
}

#[glacier::test]
async fn new_records_save_in_place() {
    each_db!(|repo| {
        let mut post = Post::new();
        assert!(post.is_new());
        post.title = "Hello".into();
        post.slug = "hello".into();
        assert!(post.save().await.unwrap());
        assert!(post.is_persisted());
        assert!(post.id > 0, "the database's id is on the record");
        assert!(!post.is_changed(), "saved means nothing pending");
        assert_eq!(Post::find(post.id).await.unwrap().title, "Hello");
    });
}

#[glacier::test]
async fn saves_only_what_changed() {
    each_db!(|repo| {
        let mut post = Post {
            title: "Old".into(),
            slug: "a".into(),
            ..Default::default()
        };
        post.save().await.unwrap();
        let mut post = Post::find(post.id).await.unwrap();
        assert!(
            post.is_persisted() && !post.is_changed(),
            "loaded records are clean"
        );

        post.title = "New".into();
        assert!(post.changed("title"));
        assert!(!post.changed("slug"));
        assert_eq!(post.was("title"), Some(Value::Text("Old".into())));
        assert_eq!(post.changes(), vec![("title", Value::Text("New".into()))]);

        // Another writer changes a column this record didn't touch...
        db::sql("UPDATE posts SET views = 9")
            .execute()
            .await
            .unwrap();
        assert!(post.save().await.unwrap());
        // ...and the save, writing only `title`, kept it.
        post.reload().await.unwrap();
        assert_eq!((post.title.as_str(), post.views), ("New", 9));
        assert_eq!(post.was("title"), Some(Value::Text("New".into())));
    });
}

#[glacier::test]
async fn invalid_records_keep_their_errors() {
    each_db!(|repo| {
        let mut post = Post::new();
        post.slug = "s".into();
        assert!(!post.save().await.unwrap());
        assert!(post.is_new());
        assert_eq!(post.errors_on("title"), ["can't be blank"]);
        assert_eq!(post.full_messages(), ["Title can't be blank"]);

        post.title = "Fixed".into();
        assert!(post.save().await.unwrap());
        assert!(post.errors().is_empty());

        let mut twin = Post {
            title: "Twin".into(),
            slug: "s".into(),
            ..Default::default()
        };
        assert!(!twin.save().await.unwrap());
        assert_eq!(twin.errors_on("slug"), ["has already been taken"]);

        // Every error at once, as Rails: a taken slug beside a blank title.
        let mut both = Post {
            slug: "s".into(),
            ..Default::default()
        };
        assert!(!both.save().await.unwrap());
        assert_eq!(both.errors_on("title"), ["can't be blank"]);
        assert_eq!(both.errors_on("slug"), ["has already been taken"]);
        // In the order the fields are declared, title before slug.
        assert_eq!(
            both.full_messages(),
            ["Title can't be blank", "Slug has already been taken"]
        );
    });
}

#[glacier::test]
async fn validations_run_once_before_the_callbacks() {
    each_db!(|repo| {
        // before_save clears the password it hashed; validating again
        // afterwards would find it missing.
        let mut account = Account {
            email: "ada@example.com".into(),
            password: Some("correct horse".into()),
            ..Default::default()
        };
        assert!(account.save().await.unwrap(), "{:?}", account.errors());
        assert_eq!(account.password_digest, "hashed:correct horse");
        let mut short = Account {
            email: "bo@example.com".into(),
            password: Some("short".into()),
            ..Default::default()
        };
        assert!(!short.save().await.unwrap());
        assert_eq!(
            short.errors_on("password"),
            ["is too short (minimum is 8 characters)"]
        );
    });
}

#[glacier::test]
async fn create_and_update_changeset_run_callbacks() {
    each_db!(|repo| {
        // As Rails' `create`: the virtual password reaches before_save.
        let account = Account::create(params(&[
            ("email", "ada@example.com"),
            ("password", "correct horse"),
        ]))
        .await
        .unwrap()
        .unwrap();
        assert_eq!(account.password_digest, "hashed:correct horse");
        // And the model's `validate do` runs.
        let invalid = Account::create(params(&[
            ("email", "bo@example.com"),
            ("password", "short"),
        ]))
        .await
        .unwrap()
        .unwrap_invalid();
        assert_eq!(
            invalid.errors_on("password"),
            ["is too short (minimum is 8 characters)"]
        );
        // An update through a changeset runs them too.
        let account = account
            .update_changeset(params(&[("password", "battery staple")]))
            .await
            .unwrap()
            .unwrap();
        assert_eq!(account.password_digest, "hashed:battery staple");
        // `changeset.insert()` is the write without callbacks.
        let raw = Account::changeset()
            .set(|a| a.email, "cy@example.com".to_owned())
            .set(|a| a.password_digest, "set by hand".to_owned())
            .insert()
            .await
            .unwrap()
            .unwrap();
        assert_eq!(raw.password_digest, "set by hand");
    });
}

#[glacier::test]
async fn builds_from_params_and_shows_bad_input_again() {
    each_db!(|repo| {
        let mut post = Post::build(params(&[
            ("title", "Hi"),
            ("slug", "hi"),
            ("views", "lots"),
        ]));
        assert_eq!(post.text("views"), "lots", "the form shows what was typed");
        assert!(!post.save().await.unwrap());
        assert_eq!(post.errors_on("views"), ["is not a number"]);

        post.assign(&params(&[("views", "5")]));
        assert_eq!(post.text("views"), "5");
        assert!(post.save().await.unwrap(), "{:?}", post.errors());
        assert_eq!(post.views, 5);

        assert!(post.update(params(&[("body", "More")])).await.unwrap());
        assert!(post.update_with(|p| p.views += 1).await.unwrap());
        let post = Post::find(post.id).await.unwrap();
        assert_eq!((post.body.as_deref(), post.views), (Some("More"), 6));
    });
}

#[test]
fn forms_target_new_and_saved_records() {
    use glacier::view::helpers::FormTarget;
    let mut post = Post::new();
    assert_eq!(post.form_action(), ("/posts".to_owned(), "post"));
    post.id = 7;
    post.__record.mark_loaded(post.values());
    assert_eq!(post.form_action(), ("/posts/7".to_owned(), "patch"));
}

async fn seed(titles: &[&str]) {
    for (i, title) in titles.iter().enumerate() {
        let mut post = Post {
            title: (*title).into(),
            slug: format!("s{i}"),
            views: i as i32,
            ..Default::default()
        };
        assert!(post.save().await.unwrap());
    }
}

#[glacier::test]
async fn shortcuts_first_last_take_pluck_ids() {
    each_db!(|repo| {
        seed(&["a", "b", "c"]).await;
        assert_eq!(Post::first().await.unwrap().unwrap().title, "a");
        assert_eq!(Post::last().await.unwrap().unwrap().title, "c");
        assert_eq!(Post::take(2).await.unwrap().len(), 2);
        let newest_first = Post::order(|p| p.views.desc());
        assert_eq!(
            newest_first.last().await.unwrap().unwrap().title,
            "a",
            "last reverses the order"
        );
        assert_eq!(
            Post::all()
                .order(|p| p.title.asc())
                .pluck(|p| p.title)
                .await
                .unwrap(),
            ["a", "b", "c"]
        );
        let ids = Post::filter(|p| p.views.ge(1)).ids().await.unwrap();
        assert_eq!(ids.len(), 2);
        assert!(Post::filter(|p| p.title.eq("b")).exists().await.unwrap());
    });
}

#[glacier::test]
async fn update_all_sets_columns_in_one_statement() {
    each_db!(|repo| {
        seed(&["a", "b", "c"]).await;
        let changed = Post::filter(|p| p.views.ge(1))
            .update_all(|p| [p.views.to(100), p.body.to(Some("bulk".to_owned()))])
            .await
            .unwrap();
        assert_eq!(changed, 2);
        assert_eq!(
            Post::all()
                .order(|p| p.views.asc())
                .pluck(|p| p.views)
                .await
                .unwrap(),
            [0, 100, 100]
        );
        assert_eq!(
            Post::filter(|p| p.body.eq(Some("bulk".to_owned())))
                .count()
                .await
                .unwrap(),
            2
        );
    });
}

#[glacier::test]
async fn bulk_writes_keep_to_the_limit() {
    each_db!(|repo| {
        seed(&["a", "b", "c"]).await;
        // Only the rows the query would load: the first by title.
        let changed = Post::all()
            .order(|p| p.title.asc())
            .limit(1)
            .update_all(|p| [p.views.to(7)])
            .await
            .unwrap();
        assert_eq!(changed, 1);
        assert_eq!(
            Post::filter(|p| p.views.eq(7))
                .pluck(|p| p.title)
                .await
                .unwrap(),
            ["a"]
        );
        let deleted = Post::all()
            .order(|p| p.title.desc())
            .limit(1)
            .offset(1)
            .delete_all()
            .await
            .unwrap();
        assert_eq!(deleted, 1);
        assert_eq!(
            Post::all()
                .order(|p| p.title.asc())
                .pluck(|p| p.title)
                .await
                .unwrap(),
            ["a", "c"]
        );
    });
}

#[glacier::test]
async fn scopes_chain() {
    each_db!(|repo| {
        for (title, views) in [("apple", 20), ("avocado", 1), ("banana", 30)] {
            let mut post = Post {
                title: title.into(),
                slug: title.into(),
                views,
                ..Default::default()
            };
            post.save().await.unwrap();
        }
        assert_eq!(Post::popular().count().await.unwrap(), 2);
        assert_eq!(Post::titled("a").count().await.unwrap(), 2);
        assert_eq!(
            Post::titled("a")
                .popular()
                .pluck(|p| p.title)
                .await
                .unwrap(),
            ["apple"]
        );
        assert_eq!(
            Post::filter(|p| p.views.lt(25))
                .popular()
                .pluck(|p| p.title)
                .await
                .unwrap(),
            ["apple"],
            "scopes chain after filter, too"
        );
    });
}

#[glacier::test]
async fn callbacks_run_in_rails_order() {
    each_db!(|repo| {
        let mut article = Article {
            title: "Hello World".into(),
            ..Default::default()
        };
        assert!(article.save().await.unwrap());
        assert_eq!(
            article.slug, "hello-world",
            "before_save's change was written"
        );
        assert_eq!(article.ran, ["after_save"]);
        assert_eq!(Article::find(article.id).await.unwrap().slug, "hello-world");

        article.ran.clear();
        article.title = "Second Title".into();
        article.save().await.unwrap();
        assert_eq!(
            Article::find(article.id).await.unwrap().slug,
            "second-title"
        );

        // Invalid: stops after validation.
        let mut blank = Article::new();
        assert!(!blank.save().await.unwrap());
        assert_eq!(blank.ran, ["before_validation"]);

        // A callback's error stops the save and comes back.
        let mut refused = Article {
            title: "fail".into(),
            ..Default::default()
        };
        assert!(refused.save().await.is_err());
        assert!(refused.is_new());

        let id = article.id;
        article.destroy().await.unwrap();
        assert_eq!(DESTROYED.load(std::sync::atomic::Ordering::SeqCst), id);
        assert_eq!(Article::count().await.unwrap(), 0);
    });
}

#[glacier::test]
async fn enumerations_are_text_columns() {
    each_db!(|repo| {
        let mut post = Post {
            title: "T".into(),
            slug: "t".into(),
            ..Default::default()
        };
        assert!(post.status.is_draft(), "the first variant is the default");
        post.save().await.unwrap();
        post.status = Status::InReview;
        post.save().await.unwrap();
        assert_eq!(Post::find(post.id).await.unwrap().status, Status::InReview);
        let stored: Vec<String> = db::sql("SELECT status FROM posts")
            .fetch_all()
            .await
            .unwrap()
            .iter()
            .map(|r| r.get("status").unwrap())
            .collect();
        assert_eq!(stored, ["in_review"]);

        assert_eq!(
            Post::filter(|p| p.status.eq(Status::InReview))
                .count()
                .await
                .unwrap(),
            1
        );
        assert_eq!(
            Post::filter(|p| p.status.eq("draft"))
                .count()
                .await
                .unwrap(),
            0
        );

        let mut bad = Post::build(params(&[("title", "B"), ("slug", "b"), ("status", "nope")]));
        assert!(!bad.save().await.unwrap());
        assert_eq!(
            bad.errors_on("status"),
            ["is not one of draft, published, in_review"]
        );
        bad.assign(&params(&[("status", "published")]));
        assert!(bad.save().await.unwrap());
        assert!(bad.status.is_published());
        assert_eq!(Status::ALL.len(), 3);
        assert_eq!(Status::Published.to_string(), "published");
    });
}

#[test]
#[should_panic(
    expected = "no Status is called `drafty`; expected one of draft, published, in_review"
)]
fn unknown_names_fail_loudly() {
    let _ = Status::from("drafty");
}