glacier-web 0.2.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Models in a second, named database. Only the analytics database has an
//! `events` table, so a query sent to the wrong one fails.

use glacier::db::{self, Repo};
use glacier::prelude::*;
use glacier::testing::TestClient;

#[glacier::model(database = "analytics", timestamps = false)]
pub struct Event {
    name: String,
}

#[glacier::model(timestamps = false)]
pub struct Post {
    title: String,
}

async fn databases() -> (Repo, Repo) {
    let main = Repo::connect("sqlite::memory:").await.unwrap();
    let analytics = Repo::connect("sqlite::memory:").await.unwrap();
    for (repo, table) in [
        (&main, "posts (id INTEGER PRIMARY KEY, title TEXT NOT NULL)"),
        (
            &analytics,
            "events (id INTEGER PRIMARY KEY, name TEXT NOT NULL)",
        ),
    ] {
        db::with(repo, db::sql(&format!("CREATE TABLE {table}")).execute())
            .await
            .unwrap();
    }
    (main, analytics)
}

fn event(name: &str) -> db::Changeset<Event> {
    Event::changeset().set(|e| e.name, name)
}

#[glacier::test]
async fn requests_reach_both_databases() {
    let (main, analytics) = databases().await;
    let app = App::new()
        .database(main)
        .named_database("analytics", analytics.clone())
        .routes(|r| {
            r.post("/posts", |_ctx| async {
                Post::create(Post::changeset().set(|p| p.title, "Hello"))
                    .await?
                    .unwrap();
                Event::create(event("post created")).await?.unwrap();
                Ok::<_, glacier::Error>(format!(
                    "{} posts, {} events",
                    Post::count().await?,
                    Event::count().await?
                ))
            });
        });
    let client = TestClient::new(app);
    let res = client.post_form("/posts", &[("x", "y")]).await;
    assert_eq!(res.body_text(), "1 posts, 1 events");
    let events = db::with_named("analytics", &analytics, Event::count()).await;
    assert_eq!(events.unwrap(), 1);
}

#[glacier::test]
async fn outside_requests_name_the_database() {
    let (main, analytics) = databases().await;
    let missing = db::with(&main, Event::count()).await.unwrap_err();
    assert!(
        missing.to_string().contains("no `analytics` database here"),
        "{missing}"
    );

    // A sandbox on the named database rolls its writes back.
    db::sandbox_named("analytics", &analytics, async {
        Event::create(event("kept for now")).await.unwrap().unwrap();
        assert_eq!(Event::count().await.unwrap(), 1);
    })
    .await
    .unwrap();

    // A transaction on it commits or rolls back on that database.
    db::with_named("analytics", &analytics, async {
        let failed: glacier::Result<()> = db::transaction_in(Some("analytics"), async {
            Event::create(event("rolled back")).await?.unwrap();
            Err(glacier::Error::internal("boom"))
        })
        .await;
        assert!(failed.is_err());
        db::transaction_in(Some("analytics"), async {
            Event::create(event("committed")).await?.unwrap();
            Ok(())
        })
        .await
        .unwrap();
        let names = Event::all().pluck(|e| e.name).await.unwrap();
        assert_eq!(names, ["committed"]);
    })
    .await;
}

#[glacier::test]
async fn config_names_the_database() {
    let config = glacier::Config::from_toml(
        glacier::Env::Test,
        "[database]\nurl = \"sqlite::memory:\"\n[databases.analytics]\nurl = \"sqlite::memory:\"\n",
    )
    .unwrap();
    let analytics = Repo::from_config_named(&config, "analytics").await.unwrap();
    assert!(!analytics.has_replica());
    assert!(Repo::from_config_named(&config, "missing").await.is_err());
}

#[glacier::test]
async fn config_databases_connect_on_first_use() {
    let path =
        std::env::temp_dir().join(format!("glacier-databases-{}.sqlite3", std::process::id()));
    let _ = std::fs::remove_file(&path);
    let url = format!("sqlite://{}?mode=rwc", path.display());
    let analytics = Repo::connect(&url).await.unwrap();
    db::with(
        &analytics,
        db::sql("CREATE TABLE events (id INTEGER PRIMARY KEY, name TEXT NOT NULL)").execute(),
    )
    .await
    .unwrap();
    let config = glacier::Config::from_toml(
        glacier::Env::Test,
        &format!("[databases.analytics]\nurl = \"{url}\"\n"),
    )
    .unwrap();
    let app = App::new().config(config).unwrap().routes(|r| {
        r.post("/events", |_ctx| async {
            Event::create(event("signed up")).await?.unwrap();
            Ok::<_, glacier::Error>(Event::count().await?.to_string())
        });
    });
    let client = TestClient::new(app);
    assert_eq!(
        client.post_form("/events", &[("x", "y")]).await.body_text(),
        "1"
    );
    assert_eq!(
        client.post_form("/events", &[("x", "y")]).await.body_text(),
        "2"
    );
    let _ = std::fs::remove_file(path);
}

#[glacier::test]
async fn named_databases_have_their_own_migrations() {
    use glacier::db::migration::{Migration, Schema};
    fn create_events(s: &mut Schema) {
        s.create_table("events", |t| {
            t.string("name").not_null();
        });
    }
    let config = glacier::Config::from_toml(
        glacier::Env::Test,
        "[databases.analytics]\nurl = \"sqlite::memory:\"\n",
    )
    .unwrap();
    let app = App::new()
        .config(config)
        .unwrap()
        .named_migrations(
            "analytics",
            vec![Migration::new("m1_create_events", create_events, |s| {
                s.drop_table("events")
            })],
        )
        .routes(|r| {
            r.post("/events", |_ctx| async {
                Event::create(event("signed up")).await?.unwrap();
                Ok::<_, glacier::Error>(Event::count().await?.to_string())
            });
        });
    let client = TestClient::new(app);
    let done = client.service().migrate_named().await.unwrap();
    assert_eq!(done, ["analytics/m1_create_events"]);
    assert!(client.service().migrate_named().await.unwrap().is_empty());
    assert_eq!(
        client.post_form("/events", &[("x", "y")]).await.body_text(),
        "1"
    );
}

#[glacier::test]
async fn seeds_load_in_one_transaction() {
    let (main, analytics) = databases().await;
    let seeded = App::new()
        .database(main.clone())
        .named_database("analytics", analytics.clone())
        .seeds(|| async {
            Post::create(Post::changeset().set(|p| p.title, "Welcome"))
                .await?
                .unwrap();
            Event::create(event("seeded")).await?.unwrap();
            Ok(())
        })
        .build();
    seeded.seed().await.unwrap();
    assert_eq!(db::with(&main, Post::count()).await.unwrap(), 1);
    assert_eq!(
        db::with_named("analytics", &analytics, Event::count())
            .await
            .unwrap(),
        1
    );

    // A failing seed leaves the app's database as it was.
    let failing = App::new()
        .database(main.clone())
        .seeds(|| async {
            Post::create(Post::changeset().set(|p| p.title, "Half"))
                .await?
                .unwrap();
            Err(glacier::Error::internal("bad seed"))
        })
        .build();
    assert!(failing.seed().await.is_err());
    assert_eq!(db::with(&main, Post::count()).await.unwrap(), 1);

    let none = App::new().database(main).build();
    assert!(
        none.seed()
            .await
            .unwrap_err()
            .to_string()
            .contains("no seeds registered")
    );
}