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();
}
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);
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");
let cleared = updated
.change()
.set(|p| p.body, None::<String>)
.update()
.await
.unwrap()
.unwrap();
assert_eq!(cleared.body, None);
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();
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);
});
}
#[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());
}