use glacier::db::migration::{Migration, Schema};
use glacier::db::{self, HasMany, Repo};
use glacier::prelude::*;
#[glacier::model]
pub struct Report {
comment: Option<String>,
#[glacier(has_many, nested, allow_destroy)]
answers: HasMany<Answer>,
}
#[glacier::model]
pub struct Answer {
report_id: Option<i64>,
parent_id: Option<i64>,
#[validate(required)]
note: String,
#[glacier(has_many, nested, foreign_key = "parent_id")]
sub_answers: HasMany<Answer>,
}
fn schema(s: &mut Schema) {
s.create_table("reports", |t| {
t.text("comment");
t.timestamps();
});
s.create_table("answers", |t| {
t.bigint("report_id");
t.bigint("parent_id");
t.text("note").not_null();
t.timestamps();
});
}
fn params(pairs: &[(&str, &str)]) -> Params {
pairs.iter().copied().collect()
}
async fn notes() -> Vec<String> {
Answer::all()
.order(|a| a.id.asc())
.pluck(|a| a.note)
.await
.unwrap()
}
#[tokio::test]
async fn updates_creates_and_destroys_children() {
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", schema, |_| {}).up_sql(repo.dialect()) {
db::sql(&statement).execute().await.unwrap();
}
let mut report = Report::new();
assert!(report.save().await.unwrap());
let created = report
.update(params(&[
("comment", "Tidy"),
(
"answers_attributes",
r#"[{"note": "Gloves"}, {"note": "Masks"}]"#,
),
]))
.await
.unwrap();
assert!(created, "{:?}", report.full_messages());
assert_eq!(notes().await, ["Gloves", "Masks"]);
let ids = Answer::all().order(|a| a.id.asc()).ids().await.unwrap();
let json = format!(
r#"{{"0": {{"id": {}, "note": "Gloves (boxed)"}}, "1": {{"id": {}, "_destroy": "1"}}}}"#,
ids[0], ids[1]
);
assert!(report
.update(params(&[("answers_attributes", &json)]))
.await
.unwrap());
assert_eq!(notes().await, ["Gloves (boxed)"]);
let id = ids[0].to_string();
assert!(report
.update(params(&[
("answers_attributes[0][id]", &id),
("answers_attributes[0][sub_answers_attributes][0][note]", "Left box"),
]))
.await
.unwrap());
let sub = Answer::filter(|a| a.parent_id.eq(Some(ids[0])))
.first()
.await
.unwrap()
.unwrap();
assert_eq!(sub.note, "Left box");
let before = notes().await;
let saved = report
.update(params(&[
("comment", "Changed"),
("answers_attributes", r#"[{"note": "Visors"}, {"note": ""}]"#),
]))
.await
.unwrap();
assert!(!saved);
assert_eq!(report.full_messages(), ["Answers note can't be blank"]);
assert_eq!(notes().await, before, "rolled back");
assert!(report.changed("comment"));
assert_eq!(report.comment.as_deref(), Some("Changed"));
let mut fresh = Report::new();
let saved = fresh
.update(params(&[("answers_attributes", r#"[{"note": ""}]"#)]))
.await
.unwrap();
assert!(!saved);
assert!(fresh.is_new(), "the rolled-back id is gone");
assert_eq!(fresh.full_messages(), ["Answers note can't be blank"]);
assert_eq!(
Report::find(report.id).await.unwrap().comment.as_deref(),
Some("Tidy")
);
let mut other = Report::new();
assert!(other.save().await.unwrap());
let stolen = format!(r#"[{{"id": {}, "note": "Mine"}}]"#, ids[0]);
let err = other
.update(params(&[("answers_attributes", &stolen)]))
.await
.unwrap_err();
assert_eq!(err.status(), StatusCode::NOT_FOUND);
let moved = format!(
r#"[{{"id": {}, "report_id": {}, "note": "Moved?"}}]"#,
ids[0], other.id
);
assert!(report
.update(params(&[("answers_attributes", &moved)]))
.await
.unwrap());
let child = Answer::find(ids[0]).await.unwrap();
assert_eq!(child.report_id, Some(report.id));
assert_eq!(child.note, "Moved?");
})
.await
.unwrap();
}
}