1
//! `start_server --database` boots against that URL, not `DATABASE_URL`.
2
//!
3
//! The URL source is process-global, so this binary holds a single test.
4

            
5
use cli_core::start_server;
6
use server::db::{DBError, admin_database_url, get_connection, use_url};
7
use sqlx::postgres::PgConnectOptions;
8
use sqlx::{ConnectOptions, Connection, PgConnection};
9

            
10
#[tokio::test]
11
1
async fn database_flag_selects_the_server_database() -> anyhow::Result<()> {
12
1
    let admin: PgConnectOptions = std::env::var("DATABASE_URL")?.parse()?;
13
1
    let name = format!("start_url_{}", uuid::Uuid::new_v4().simple());
14
1
    let mut admin_conn = PgConnection::connect_with(&admin).await?;
15
1
    sqlx::raw_sql(sqlx::AssertSqlSafe(format!("CREATE DATABASE {name}")))
16
1
        .execute(&mut admin_conn)
17
1
        .await?;
18
1
    let url = admin.database(&name).to_url_lossy().to_string();
19

            
20
1
    let outcome = boot_and_probe(&url, &name).await;
21

            
22
    // The server pool is still open; FORCE drops its connections.
23
1
    sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
24
1
        "DROP DATABASE {name} WITH (FORCE)"
25
1
    )))
26
1
    .execute(&mut admin_conn)
27
1
    .await?;
28
2
    outcome
29
1
}
30

            
31
1
async fn boot_and_probe(url: &str, name: &str) -> anyhow::Result<()> {
32
1
    start_server(Some(url.to_owned()), None).await?;
33

            
34
    // ensure! rather than assert!, so a failure still reaches the caller's DROP.
35
1
    anyhow::ensure!(admin_database_url()? == url, "server resolved another URL");
36
1
    let mut conn = get_connection().await?;
37
1
    let connected: String = sqlx::query_scalar("SELECT current_database()")
38
1
        .fetch_one(&mut *conn)
39
1
        .await?;
40
1
    anyhow::ensure!(connected == name, "pool connected to {connected}");
41
1
    anyhow::ensure!(
42
1
        matches!(use_url(url.to_owned()), Err(DBError::UrlAlreadyResolved)),
43
        "a second use_url was accepted"
44
    );
45
1
    Ok(())
46
1
}