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
//! The ORM, run against SQLite (in memory) and, when
//! `GLACIER_TEST_POSTGRES_URL` is set, Postgres too. Each test runs in a
//! rolled-back sandbox, so Postgres runs leave nothing behind.

use glacier::db::{self, Changeset, Dialect, Repo, Timestamp, Value};
use glacier::prelude::*;
use glacier::testing::TestClient;
use serde::Deserialize;

#[derive(Debug, Clone, Model)]
struct Post {
    id: i64,
    title: String,
    slug: String,
    views: i64,
    body: Option<String>,
    published: bool,
    inserted_at: Timestamp,
    updated_at: Timestamp,
}

#[derive(Deserialize)]
struct PostForm {
    title: String,
    slug: String,
}

impl From<PostForm> for Changeset<Post> {
    fn from(form: PostForm) -> Self {
        Post::changeset()
            .set(|p| p.title, form.title)
            .set(|p| p.slug, form.slug)
            .validate_required(|p| p.title)
            .validate_length(|p| p.title, 3..=40)
            .unique(|p| p.slug)
    }
}

fn form(title: &str, slug: &str) -> PostForm {
    PostForm {
        title: title.into(),
        slug: slug.into(),
    }
}

async fn create_table(dialect: Dialect) {
    let ddl = match dialect {
        Dialect::Sqlite => {
            "CREATE TABLE posts (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                title TEXT NOT NULL,
                slug TEXT NOT NULL UNIQUE,
                views BIGINT NOT NULL DEFAULT 0,
                body TEXT,
                published BOOLEAN NOT NULL DEFAULT FALSE,
                inserted_at TEXT NOT NULL,
                updated_at TEXT NOT NULL
            )"
        }
        Dialect::Postgres => {
            "CREATE TABLE posts (
                id BIGSERIAL PRIMARY KEY,
                title TEXT NOT NULL,
                slug TEXT NOT NULL UNIQUE,
                views BIGINT NOT NULL DEFAULT 0,
                body TEXT,
                published BOOLEAN NOT NULL DEFAULT FALSE,
                inserted_at TIMESTAMPTZ NOT NULL,
                updated_at TIMESTAMPTZ NOT NULL
            )"
        }
    };
    db::sql(ddl).execute().await.unwrap();
}

/// Runs `test` once per available database, inside a rolled-back sandbox
/// with a fresh `posts` table.
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 {
                create_table($repo.dialect()).await;
                $body
            })
            .await
            .unwrap();
        }
    }};
}

#[tokio::test]
async fn creates_and_finds_records() {
    each_db!(|repo| {
        let before = chrono::Utc::now();
        let post = Post::create(form("Hello", "hello")).await.unwrap().unwrap();
        assert!(post.id > 0);
        assert_eq!(post.title, "Hello");
        assert_eq!(post.views, 0, "database defaults are returned");
        assert_eq!(post.body, None);
        assert!(!post.published);
        assert!(post.inserted_at >= before - chrono::Duration::seconds(1));
        assert_eq!(post.inserted_at, post.updated_at);

        let found = Post::find(post.id).await.unwrap();
        assert_eq!(found.slug, "hello");
        assert_eq!(Post::count().await.unwrap(), 1);

        let missing = Post::find(999_999).await.unwrap_err();
        assert_eq!(missing.status(), StatusCode::NOT_FOUND);
    });
}

#[tokio::test]
async fn validation_errors_come_back_on_the_changeset() {
    each_db!(|repo| {
        let changeset = Post::create(form("  ", "x"))
            .await
            .unwrap()
            .unwrap_invalid();
        assert_eq!(changeset.errors_on("title"), ["can't be blank"]);
        assert_eq!(
            changeset.text("slug"),
            "x",
            "input is kept to refill the form"
        );

        let changeset = Post::create(form("Hi", "y"))
            .await
            .unwrap()
            .unwrap_invalid();
        assert_eq!(
            changeset.full_messages(),
            ["Title is too short (minimum is 3 characters)"]
        );
        assert_eq!(Post::count().await.unwrap(), 0, "nothing was written");
    });
}

#[tokio::test]
async fn unique_violations_become_changeset_errors() {
    each_db!(|repo| {
        Post::create(form("First", "same")).await.unwrap().unwrap();
        let changeset = Post::create(form("Second", "same"))
            .await
            .unwrap()
            .unwrap_invalid();
        assert_eq!(changeset.errors_on("slug"), ["has already been taken"]);
        assert_eq!(Post::count().await.unwrap(), 1);
    });
}

async fn seed() {
    for (title, slug, views) in [
        ("Rust tips", "rust-tips", 120),
        ("Elixir tips", "elixir-tips", 80),
        ("Rust async", "rust-async", 300),
        ("Gardening", "gardening", 5),
    ] {
        let post = Post::create(form(title, slug)).await.unwrap().unwrap();
        post.change()
            .set(|p| p.views, views)
            .update()
            .await
            .unwrap()
            .unwrap();
    }
}

fn titles(posts: Vec<Post>) -> Vec<String> {
    posts.into_iter().map(|p| p.title).collect()
}

#[tokio::test]
async fn queries_filter_order_and_page() {
    each_db!(|repo| {
        seed().await;

        let popular = Post::filter(|p| p.views.gt(100))
            .order(|p| p.views.desc())
            .await
            .unwrap();
        assert_eq!(titles(popular), ["Rust async", "Rust tips"]);

        let rust = Post::filter(|p| p.title.like("Rust%"))
            .filter(|p| p.views.lt(200))
            .await
            .unwrap();
        assert_eq!(titles(rust), ["Rust tips"]);

        let either = Post::filter(|p| p.slug.eq("gardening").or(p.views.eq(80)))
            .order(|p| p.title.asc())
            .await
            .unwrap();
        assert_eq!(titles(either), ["Elixir tips", "Gardening"]);

        let page = Post::order(|p| p.views.asc())
            .limit(2)
            .offset(1)
            .await
            .unwrap();
        assert_eq!(titles(page), ["Elixir tips", "Rust tips"]);
        let skipped = Post::order(|p| p.views.asc()).offset(3).await.unwrap();
        assert_eq!(titles(skipped), ["Rust async"]);

        let some = Post::filter(|p| p.slug.is_in(["gardening", "rust-tips"]))
            .count()
            .await
            .unwrap();
        assert_eq!(some, 2);
        assert_eq!(
            Post::filter(|p| p.slug.is_in(Vec::<String>::new()))
                .count()
                .await
                .unwrap(),
            0
        );

        let not_rust = Post::filter(|p| p.title.like("Rust%").not())
            .count()
            .await
            .unwrap();
        assert_eq!(not_rust, 2);

        assert!(Post::body_is_null_count().await == 4);
        let first = Post::all().first().await.unwrap().unwrap();
        assert_eq!(first.slug, "rust-tips", "first() orders by id");
        let found = Post::find_by(|p| p.slug.eq("gardening")).await.unwrap();
        assert_eq!(found.unwrap().views, 5);
        assert!(
            Post::find_by(|p| p.slug.eq("nope"))
                .await
                .unwrap()
                .is_none()
        );
        assert!(Post::filter(|p| p.views.ge(300)).exists().await.unwrap());

        let raw = Post::filter(|_| {
            glacier::db::Expr::raw("lower(title) = ?", [Value::Text("gardening".into())])
        })
        .count()
        .await
        .unwrap();
        assert_eq!(raw, 1);

        let deleted = Post::filter(|p| p.views.lt(100))
            .delete_all()
            .await
            .unwrap();
        assert_eq!(deleted, 2);
        assert_eq!(Post::count().await.unwrap(), 2);
    });
}

trait PostQueries {
    async fn body_is_null_count() -> i64;
}

impl PostQueries for Post {
    async fn body_is_null_count() -> i64 {
        Post::filter(|p| p.body.is_null()).count().await.unwrap()
    }
}

#[tokio::test]
async fn updates_only_what_changed() {
    each_db!(|repo| {
        let post = Post::create(form("Draft", "draft")).await.unwrap().unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(5)).await;

        let updated = post
            .clone()
            .change()
            .set(|p| p.published, true)
            .set(|p| p.body, Some("Words".to_owned()))
            .update()
            .await
            .unwrap()
            .unwrap();
        assert!(updated.published);
        assert_eq!(updated.body.as_deref(), Some("Words"));
        assert_eq!(updated.title, "Draft");
        assert!(updated.updated_at > post.updated_at);
        assert_eq!(updated.inserted_at, post.inserted_at);

        // Updating through a form runs its validations.
        let invalid = updated
            .clone()
            .update_changeset(form("", "draft"))
            .await
            .unwrap()
            .unwrap_invalid();
        assert_eq!(invalid.errors_on("title"), ["can't be blank"]);
        assert_eq!(invalid.data().unwrap().title, "Draft");

        // Setting a column back to NULL works on both databases.
        let cleared = updated
            .change()
            .set(|p| p.body, None::<String>)
            .update()
            .await
            .unwrap()
            .unwrap();
        assert_eq!(cleared.body, None);

        // No changes: no query, same record back.
        let same = cleared.clone().change().update().await.unwrap().unwrap();
        assert_eq!(same.updated_at, cleared.updated_at);

        cleared.delete().await.unwrap();
        assert_eq!(Post::count().await.unwrap(), 0);
    });
}

#[tokio::test]
async fn raw_sql_reads_rows() {
    each_db!(|repo| {
        seed().await;
        let rows = db::sql("SELECT title, views FROM posts WHERE views > ? ORDER BY views")
            .bind(100)
            .fetch_all()
            .await
            .unwrap();
        let first: (String, i64) = (rows[0].get("title").unwrap(), rows[0].get("views").unwrap());
        assert_eq!(first, ("Rust tips".to_owned(), 120));
        assert_eq!(rows.len(), 2);
    });
}

#[tokio::test]
async fn raw_sql_reads_values() {
    each_db!(|repo| {
        seed().await;
        let views: Vec<i64> = db::sql("SELECT views FROM posts WHERE views > ? ORDER BY views")
            .bind(100)
            .values()
            .await
            .unwrap();
        assert_eq!(views.len(), 2);
        assert_eq!(views[0], 120);
        let title: Option<String> = db::sql("SELECT title FROM posts ORDER BY views DESC")
            .value()
            .await
            .unwrap();
        assert!(title.is_some());
        let none: Option<String> = db::sql("SELECT title FROM posts WHERE views < 0")
            .value()
            .await
            .unwrap();
        assert_eq!(none, None);
    });
}

#[tokio::test]
async fn transactions_commit_or_roll_back() {
    let repo = Repo::connect("sqlite::memory:").await.unwrap();
    db::with(&repo, async {
        create_table(Dialect::Sqlite).await;

        let result: glacier::Result<()> = db::transaction(async {
            Post::create(form("Kept", "kept")).await?.unwrap();
            Ok(())
        })
        .await;
        result.unwrap();

        let result: glacier::Result<()> = db::transaction(async {
            Post::create(form("Lost", "lost")).await?.unwrap();
            Err(Error::bad_request("changed my mind"))
        })
        .await;
        assert!(result.is_err());

        let titles = titles(Post::all().await.unwrap());
        assert_eq!(titles, ["Kept"]);
    })
    .await;
}

#[tokio::test]
async fn explicit_connections_and_missing_ones() {
    let err = Post::all().await.unwrap_err();
    assert!(err.message().contains("no database connection"), "{err}");

    let repo = Repo::connect("sqlite::memory:").await.unwrap();
    db::sql("CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT, slug TEXT, views BIGINT, body TEXT, published BOOLEAN, inserted_at TEXT, updated_at TEXT)")
        .on(&repo)
        .execute()
        .await
        .unwrap();
    // `.on(..)` works with no ambient connection at all.
    assert!(Post::all().on(&repo).await.unwrap().is_empty());
}

#[test]
fn renders_queries() {
    let (sql, values) = Post::filter(|p| p.views.gt(10).and(p.body.is_null()))
        .order(|p| p.inserted_at.desc())
        .limit(5)
        .to_sql(Dialect::Postgres);
    assert_eq!(
        sql,
        r#"SELECT * FROM "posts" WHERE ("views" > $1 AND "body" IS NULL) ORDER BY "inserted_at" DESC LIMIT 5"#
    );
    assert_eq!(values, [Value::Int(10)]);
}

#[tokio::test]
async fn requests_use_the_app_database() {
    each_db!(|repo| {
        let c = TestClient::new(App::new().database(repo.clone()).routes(|r| {
            r.post("/posts", |ctx: Context| async move {
                match Post::create(ctx.form::<PostForm>()?).await? {
                    Saved(post) => glacier::redirect!(post),
                    Invalid(changeset) => Ok(Response::text(changeset.full_messages().join(", "))
                        .with_status(StatusCode::UNPROCESSABLE_ENTITY)),
                }
            })
            .get("/posts/:id", |ctx: Context| async move {
                let post = Post::find(ctx.id()?).await?;
                Ok::<_, Error>(post.title)
            });
        }));

        let res = c
            .post_form("/posts", &[("title", "Via HTTP"), ("slug", "via-http")])
            .await;
        assert_eq!(res.status(), StatusCode::SEE_OTHER);
        let location = res.header("location").unwrap().to_owned();
        assert_eq!(c.get(&location).await.body_text(), "Via HTTP");

        let res = c.post_form("/posts", &[("title", ""), ("slug", "x")]).await;
        assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY);
        assert_eq!(res.body_text(), "Title can't be blank");

        assert_eq!(c.get("/posts/424242").await.status(), StatusCode::NOT_FOUND);
    });
}

/// Other libraries can share Glacier's pool: here raw sqlx, through the
/// re-exported crate, sees rows Glacier wrote and vice versa.
#[tokio::test]
async fn shares_the_pool_with_sqlx() {
    let repo = glacier::db::Repo::connect("sqlite::memory:").await.unwrap();
    let pool = repo.sqlite_pool().expect("a SQLite repo").clone();
    glacier::sqlx::query("CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT)")
        .execute(&pool)
        .await
        .unwrap();
    glacier::db::sql("INSERT INTO notes (body) VALUES (?)")
        .bind("from glacier")
        .on(&repo)
        .execute()
        .await
        .unwrap();
    let (body,): (String,) = glacier::sqlx::query_as("SELECT body FROM notes")
        .fetch_one(&pool)
        .await
        .unwrap();
    assert_eq!(body, "from glacier");
    #[cfg(feature = "postgres")]
    assert!(repo.postgres_pool().is_none());
}