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 {
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))
}
}
#[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(())
}
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();
});
}
#[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()))]);
db::sql("UPDATE posts SET views = 9")
.execute()
.await
.unwrap();
assert!(post.save().await.unwrap());
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"]);
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"]);
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| {
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| {
let account = Account::create(params(&[
("email", "ada@example.com"),
("password", "correct horse"),
]))
.await
.unwrap()
.unwrap();
assert_eq!(account.password_digest, "hashed:correct horse");
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)"]
);
let account = account
.update_changeset(params(&[("password", "battery staple")]))
.await
.unwrap()
.unwrap();
assert_eq!(account.password_digest, "hashed:battery staple");
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(¶ms(&[("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;
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"
);
let mut blank = Article::new();
assert!(!blank.save().await.unwrap());
assert_eq!(blank.ran, ["before_validation"]);
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(¶ms(&[("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");
}