use glacier::db::migration::{Migration, Schema};
use glacier::db::{self, Repo};
use glacier::prelude::*;
use glacier::testing::TestClient;
use glacier::view::helpers::link_to;
fn too_shouty(value: Option<&glacier::db::Value>) -> Option<String> {
let text = value?.to_text();
(text.len() > 3 && text == text.to_uppercase()).then(|| "is too shouty".to_owned())
}
#[glacier::model]
pub struct Post {
#[validate(required, length = 3..=40, with = too_shouty)]
title: String,
#[validate(unique)]
slug: String,
body: Option<String>,
published: bool,
views: i32,
#[glacier(protected)]
featured: bool,
}
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.boolean("published").not_null().default(false);
t.integer("views").not_null().default(0);
t.boolean("featured").not_null().default(false);
t.timestamps();
});
}
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()
}
#[test]
fn model_adds_id_timestamps_and_pub_fields() {
assert_eq!(
Post::COLUMNS,
&[
"id",
"title",
"slug",
"body",
"published",
"views",
"featured",
"inserted_at",
"updated_at"
]
);
assert_eq!(
(Post::CREATED_AT, Post::UPDATED_AT),
(Some("inserted_at"), Some("updated_at"))
);
}
#[tokio::test]
async fn params_are_cast_validated_and_saved() {
each_db!(|repo| {
let post = Post::create(params(&[
("title", "Hello"),
("slug", "hello"),
("body", ""),
("published", "on"),
("views", " 12 "),
]))
.await
.unwrap()
.unwrap();
assert_eq!(post.title, "Hello");
assert_eq!(post.body, None, "empty text casts to None");
assert!(post.published);
assert_eq!(post.views, 12);
let invalid = Post::create(params(&[
("title", "SHOUTING"),
("slug", "x"),
("views", "lots"),
("published", "maybe"),
]))
.await
.unwrap()
.unwrap_invalid();
assert_eq!(invalid.errors_on("views"), ["is not a number"]);
assert_eq!(invalid.text("views"), "lots");
assert_eq!(invalid.errors_on("published"), ["is invalid"]);
assert_eq!(invalid.errors_on("title"), ["is too shouty"]);
let blank = Post::changeset()
.set(|p| p.slug, "blank")
.insert()
.await
.unwrap();
let Invalid(blank) = blank else {
panic!("expected errors")
};
assert_eq!(blank.errors_on("title"), ["can't be blank"]);
let duplicate = Post::create(params(&[("title", "Again"), ("slug", "hello")]))
.await
.unwrap()
.unwrap_invalid();
assert_eq!(duplicate.errors_on("slug"), ["has already been taken"]);
let both = Post::create(params(&[("title", "Hi"), ("slug", "hello")]))
.await
.unwrap()
.unwrap_invalid();
assert_eq!(
both.errors_on("title"),
["is too short (minimum is 3 characters)"]
);
assert_eq!(both.errors_on("slug"), ["has already been taken"]);
});
}
#[tokio::test]
async fn protected_fields_are_not_mass_assignable() {
each_db!(|repo| {
let post = Post::create(params(&[
("title", "Sneaky"),
("slug", "sneaky"),
("featured", "true"),
("id", "999"),
]))
.await
.unwrap()
.unwrap();
assert!(!post.featured);
assert_ne!(post.id, 999);
});
}
#[tokio::test]
async fn updates_only_touch_submitted_fields() {
each_db!(|repo| {
let post = Post::create(params(&[
("title", "Draft"),
("slug", "draft"),
("views", "5"),
]))
.await
.unwrap()
.unwrap();
let post = post
.update_changeset(params(&[("published", "false"), ("published", "true")]))
.await
.unwrap()
.unwrap();
assert!(
post.published,
"the last value wins, so hidden-false + checkbox works"
);
assert_eq!(post.views, 5, "absent fields are left alone");
assert_eq!(post.title, "Draft");
match post
.update_changeset(params(&[("title", "")]))
.await
.unwrap()
{
Saved(_) => panic!("blank title must be invalid"),
Invalid(changeset) => {
assert_eq!(changeset.errors_on("title"), ["can't be blank"]);
assert_eq!(changeset.data().unwrap().title, "Draft");
}
}
});
}
#[tokio::test]
async fn records_know_their_urls() {
each_db!(|repo| {
let post = Post::create(params(&[("title", "Links & things"), ("slug", "links")]))
.await
.unwrap()
.unwrap();
let id = post.id;
assert_eq!(post.to_path(), format!("/posts/{id}"));
assert_eq!(Post::collection_path(), "/posts");
assert_eq!(
link_to(&post.title, &post).0,
format!(r#"<a href="/posts/{id}">Links & things</a>"#)
);
assert_eq!(link_to("All", "/posts").0, r#"<a href="/posts">All</a>"#);
});
}
pub struct Posts;
#[glacier::controller]
impl Posts {
async fn create(ctx: Context) {
match Post::create(ctx.params()).await? {
Saved(post) => redirect!(post, notice: "Post created."),
Invalid(changeset) => Ok(Response::text(changeset.full_messages().join(", "))
.with_status(StatusCode::UNPROCESSABLE_ENTITY)),
}
}
async fn new() {
Ok(html!("{{ form_for(&Post::changeset()) }}</form>").into_response())
}
async fn edit(ctx: Context) {
let post = Post::find(ctx.id()?).await?;
Ok(html!("{{ form_for(&post.change()) }}</form>").into_response())
}
}
#[tokio::test]
async fn controllers_save_from_params_and_redirect_to_records() {
each_db!(|repo| {
let c = TestClient::new(App::new().database(repo.clone()).routes(|r| {
r.resources::<Posts>("posts");
}));
let new_form = c.get("/posts/new").await.body_text();
assert!(
new_form.starts_with(r#"<form method="post" action="/posts">"#),
"{new_form}"
);
let res = c
.post_form(
"/posts",
&[
("title", "Via form"),
("slug", "via-form"),
("published", "on"),
],
)
.await;
assert_eq!(res.status(), StatusCode::SEE_OTHER);
let location = res.header("location").unwrap().to_owned();
assert!(location.starts_with("/posts/"), "{location}");
let edit_form = c.get(&format!("{location}/edit")).await.body_text();
assert!(
edit_form.starts_with(&format!(r#"<form method="post" action="{location}">"#)),
"{edit_form}"
);
assert!(
edit_form.contains(r#"name="_method" value="patch""#),
"{edit_form}"
);
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");
});
}
#[tokio::test]
async fn params_merge_query_body_and_path() {
let c = TestClient::new(App::new().routes(|r| {
r.post("/things/:id", |ctx: Context| async move {
let p = ctx.params();
format!(
"{} {} {}",
p.get("id").unwrap_or("-"),
p.get("q").unwrap_or("-"),
p.get("name").unwrap_or("-")
)
});
}));
let res = c
.post_form("/things/7?q=search&id=wrong", &[("name", "form")])
.await;
assert_eq!(res.body_text(), "7 search form", "path params win");
let res = c
.post_json("/things/8", &serde_json::json!({ "name": "json", "n": 3 }))
.await;
assert_eq!(res.body_text(), "8 - json");
}
#[tokio::test]
async fn aggregates_and_groups() {
each_db!(|repo| {
for (slug, views, published) in [("a", 3, true), ("b", 5, false), ("c", 10, true)] {
Post::create(params(&[
("title", &format!("Post {slug}")),
("slug", slug),
("views", &views.to_string()),
("published", &published.to_string()),
]))
.await
.unwrap()
.unwrap();
}
assert_eq!(Post::sum(|p| p.views).await.unwrap(), 18);
assert_eq!(
Post::filter(|p| p.published.eq(true))
.sum(|p| p.views)
.await
.unwrap(),
13
);
assert_eq!(
Post::filter(|p| p.views.gt(100))
.sum(|p| p.views)
.await
.unwrap(),
0,
"nothing sums to 0"
);
assert_eq!(Post::average(|p| p.views).await.unwrap(), Some(6.0));
assert_eq!(Post::minimum(|p| p.views).await.unwrap(), Some(3));
assert_eq!(
Post::maximum(|p| p.title).await.unwrap().as_deref(),
Some("Post c")
);
assert_eq!(
Post::filter(|p| p.views.gt(100))
.maximum(|p| p.views)
.await
.unwrap(),
None
);
assert_eq!(
Post::group(|p| p.published).count().await.unwrap(),
vec![(false, 1), (true, 2)]
);
assert_eq!(
Post::group(|p| p.published).sum(|p| p.views).await.unwrap(),
vec![(false, 5), (true, 13)]
);
assert_eq!(
Post::all()
.group(|p| p.published)
.maximum(|p| p.views)
.await
.unwrap(),
vec![(false, Some(5)), (true, Some(10))]
);
assert_eq!(
Post::all()
.distinct()
.order(|p| p.published.asc())
.pluck(|p| p.published)
.await
.unwrap(),
vec![false, true]
);
});
}
#[tokio::test]
async fn find_or_create_by() {
each_db!(|repo| {
let set_up = |p: &mut Post| {
p.title = "Hello".into();
p.slug = "hello".into();
};
let created = Post::find_or_create_by(|p| p.slug.eq("hello"), set_up)
.await
.unwrap();
assert!(created.id > 0, "saved");
let found = Post::find_or_create_by(|p| p.slug.eq("hello"), set_up)
.await
.unwrap();
assert_eq!(found.id, created.id, "found, not created again");
assert_eq!(Post::count().await.unwrap(), 1);
let fresh = Post::find_or_initialize_by(|p| p.slug.eq("new"), |p| p.slug = "new".into())
.await
.unwrap();
assert_eq!(
(fresh.id, fresh.slug.as_str()),
(0, "new"),
"built, not saved"
);
let invalid = Post::find_or_create_by(|p| p.slug.eq("x"), |p| p.slug = "x".into())
.await
.unwrap();
assert_eq!(invalid.id, 0, "invalid: not saved");
assert!(!invalid.full_messages().is_empty(), "with its errors");
assert_eq!(Post::count().await.unwrap(), 1);
});
}
#[glacier::model]
pub struct Listing {
#[validate(format = "^[a-z0-9-]+$")]
slug: String,
#[validate(inclusion = ["draft", "published"])]
status: String,
#[validate(numericality(greater_than = 0, only_integer))]
quantity: i32,
#[validate(numericality(greater_than_or_equal_to = 0, less_than_or_equal_to = 100))]
discount: Option<f64>,
}
#[tokio::test]
async fn format_inclusion_and_numericality() {
each_db!(|repo| {
let listings = |s: &mut Schema| {
s.create_table("listings", |t| {
t.string("slug").not_null();
t.string("status").not_null();
t.integer("quantity").not_null();
t.float("discount");
t.timestamps();
});
};
for statement in Migration::new("m2_listings", listings, |_| {}).up_sql(repo.dialect()) {
db::sql(&statement).execute().await.unwrap();
}
let mut invalid = Listing::build(params(&[
("slug", "Not A Slug"),
("status", "archived"),
("quantity", "0"),
("discount", "120.5"),
]));
assert!(!invalid.save().await.unwrap());
assert_eq!(
invalid.full_messages(),
[
"Slug is invalid",
"Status is not included in the list",
"Quantity must be greater than 0",
"Discount must be less than or equal to 100"
]
);
let mut fractional = Listing::build(params(&[
("slug", "a"),
("status", "draft"),
("quantity", "1"),
("discount", "-0.5"),
]));
assert!(!fractional.save().await.unwrap());
assert_eq!(
fractional.full_messages(),
["Discount must be greater than or equal to 0"]
);
let mut valid = Listing::build(params(&[
("slug", "red-shoes"),
("status", "draft"),
("quantity", "3"),
]));
assert!(valid.save().await.unwrap(), "{:?}", valid.full_messages());
});
}
#[tokio::test]
async fn cursor_pages_walk_forward_and_back() {
use glacier::pagination::CursorPage;
each_db!(|repo| {
for (i, views) in [5, 3, 5, 9, 3, 5, 1].into_iter().enumerate() {
Post::create(params(&[
("title", &format!("Post {i}")),
("slug", &format!("p{i}")),
("views", &views.to_string()),
]))
.await
.unwrap()
.unwrap();
}
let expected: Vec<i64> = Post::all()
.order(|p| p.views.desc())
.order(|p| p.id.desc())
.ids()
.await
.unwrap();
let page_of = |cursor: Option<String>| {
let mut params = Params::default();
params.insert("per_page", "3");
if let Some(cursor) = cursor {
params.insert("cursor", cursor);
}
CursorPage::from_params(¶ms, 20, 100).unwrap()
};
let mut seen = Vec::new();
let mut cursor = None;
let last_prev = loop {
let page = Post::all()
.order(|p| p.views.desc())
.cursor(page_of(cursor.clone()))
.await
.unwrap();
assert!(page.records.len() <= 3);
seen.extend(page.records.iter().map(|p| p.id));
match page.next {
Some(next) => cursor = Some(next),
None => break page.prev,
}
};
assert_eq!(seen, expected, "every post once, in order");
let back = Post::all()
.order(|p| p.views.desc())
.cursor(page_of(last_prev))
.await
.unwrap();
assert_eq!(
back.records.iter().map(|p| p.id).collect::<Vec<_>>(),
expected[3..6],
"the middle page"
);
assert!(back.next.is_some() && back.prev.is_some());
let first = Post::all()
.order(|p| p.views.desc())
.cursor(page_of(None))
.await
.unwrap();
Post::create(params(&[
("title", "New top"),
("slug", "new"),
("views", "100"),
]))
.await
.unwrap()
.unwrap();
let second = Post::all()
.order(|p| p.views.desc())
.cursor(page_of(first.next.clone()))
.await
.unwrap();
assert_eq!(
second.records.iter().map(|p| p.id).collect::<Vec<_>>(),
expected[3..6]
);
assert!(first.prev.is_none(), "the first page has no previous");
let mut batches = Post::all().order(|p| p.views.desc()).batches(3);
let mut sizes = Vec::new();
let mut total = 0;
while let Some(batch) = batches.next().await.unwrap() {
sizes.push(batch.len());
total += batch.len();
}
assert_eq!((sizes, total), (vec![3, 3, 2], 8));
let estimate = Post::all().estimated_count().await.unwrap();
assert!(estimate == 8 || repo.dialect() == glacier::db::Dialect::Postgres);
assert_eq!(
Post::filter(|p| p.views.gt(4))
.estimated_count()
.await
.unwrap(),
5,
"filtered: exact"
);
});
}
#[tokio::test]
async fn multi_step_transactions() {
use glacier::db::{Failure, Multi};
let post =
|title: &str, slug: &str| Post::from_params(¶ms(&[("title", title), ("slug", slug)]));
each_db!(|repo| {
let done = Multi::new()
.insert("first", post("First post", "first"))
.run("second", |done| async move {
let first: &Post = done.get("first").unwrap();
let title = format!("After {}", first.title);
Post::create(params(&[("title", &title), ("slug", "second")]))
.await?
.into_step()
})
.commit()
.await
.unwrap();
assert_eq!(done.steps(), ["first", "second"]);
assert_eq!(
done.get::<Post>("second").unwrap().title,
"After First post"
);
assert_eq!(Post::count().await.unwrap(), 2);
let failed = Multi::new()
.insert("ok", post("Fine", "fine"))
.insert("bad", post("", "bad"))
.insert("never", post("Never", "never"))
.commit()
.await
.unwrap_err();
assert_eq!(failed.step, "bad");
assert_eq!(failed.completed, ["ok"]);
let Failure::Invalid { messages, errors } = &failed.failure else {
panic!("{failed}")
};
assert_eq!(messages, &["Title can't be blank"]);
assert_eq!(errors["title"][0], "can't be blank");
assert_eq!(Post::count().await.unwrap(), 2, "rolled back");
assert_eq!(
glacier::Error::from(failed).status(),
StatusCode::UNPROCESSABLE_ENTITY
);
let failed = Multi::new()
.insert("ok", post("Also fine", "also"))
.run("boom", |_| async {
Err::<(), _>(Failure::Error(glacier::Error::internal("boom")))
})
.commit()
.await
.unwrap_err();
assert_eq!(
(failed.step.as_str(), failed.to_string()),
("boom", "step `boom` failed: boom".into())
);
assert_eq!(Post::count().await.unwrap(), 2);
});
}
impl Post {
fn draft(params: &Params) -> db::Changeset<Post> {
let changeset = db::Changeset::<Post>::new()
.cast(|p| p.title, params)
.cast(|p| p.slug, params);
glacier::validate!(changeset, slug, required, format = "^[a-z-]+$")
}
fn feature(params: &Params) -> db::Changeset<Post> {
db::Changeset::<Post>::new().cast(|p| p.featured, params)
}
}
#[tokio::test]
async fn named_changesets() {
each_db!(|repo| {
let invalid = Post::create(Post::draft(¶ms(&[
("title", ""),
("slug", "Not Words"),
("body", "ignored"),
])))
.await
.unwrap()
.unwrap_invalid();
assert_eq!(
invalid.full_messages(),
["Slug is invalid", "Title can't be blank"]
);
let post = Post::create(Post::draft(¶ms(&[
("title", "Hello"),
("slug", "hello"),
("body", "ignored"),
])))
.await
.unwrap()
.unwrap();
assert_eq!(post.body, None);
let post = post
.update_changeset(params(&[("featured", "true")]))
.await
.unwrap()
.unwrap();
assert!(!post.featured);
let post = post
.update_changeset(Post::feature(¶ms(&[("featured", "true")])))
.await
.unwrap()
.unwrap();
assert!(post.featured);
assert_eq!(post.title, "Hello", "untouched fields kept");
});
}
#[tokio::test]
async fn sorting_by_allowed_params() {
each_db!(|repo| {
for (title, slug, views) in [
("Bravo", "b", "5"),
("Alpha", "a", "5"),
("Charlie", "c", "1"),
] {
Post::create(params(&[
("title", title),
("slug", slug),
("views", views),
]))
.await
.unwrap()
.unwrap();
}
let titles = |sort: &str| {
let sort = sort.to_owned();
async move {
Post::order(|p| p.slug.desc())
.sort(¶ms(&[("sort", &sort)]), ["title", "views"])?
.pluck(|p| p.title)
.await
}
};
assert_eq!(
titles("").await.unwrap(),
["Charlie", "Bravo", "Alpha"],
"default order"
);
assert_eq!(
titles("title").await.unwrap(),
["Alpha", "Bravo", "Charlie"]
);
assert_eq!(
titles("-title").await.unwrap(),
["Charlie", "Bravo", "Alpha"]
);
assert_eq!(
titles("views,-title").await.unwrap(),
["Charlie", "Bravo", "Alpha"]
);
assert_eq!(
titles("-views, title").await.unwrap(),
["Alpha", "Bravo", "Charlie"]
);
let refused = titles("slug").await.unwrap_err();
assert_eq!(refused.status(), StatusCode::BAD_REQUEST);
assert_eq!(
refused.message(),
"can't sort by `slug`; sort by `title`, `views`"
);
assert!(titles("title;drop").await.is_err());
});
}
#[tokio::test]
async fn find_takes_an_id_as_text() {
each_db!(|repo| {
let mut post = Post::new();
post.title = "Hello".into();
post.slug = "hello".into();
assert!(post.save().await.unwrap());
let id = post.id.to_string();
assert_eq!(
Post::find(id.as_str()).await.unwrap().id,
post.id,
"a param"
);
assert_eq!(
Post::find(format!(" {id} ")).await.unwrap().id,
post.id,
"trimmed"
);
for bad in ["abc", "", "1.5"] {
let error = Post::find(bad).await.unwrap_err();
assert_eq!(error.status(), 404, "{bad:?} is not found");
}
});
}