use ferro_rs::validation::ConstraintMap;
use sea_orm::{ConnectionTrait, Database, Statement};
fn pg_url() -> String {
std::env::var("DATABASE_URL")
.unwrap_or_else(|_| "postgres://alberto@localhost:5432/postgres".to_owned())
}
async fn exec(db: &sea_orm::DatabaseConnection, sql: &str) -> Result<(), sea_orm::DbErr> {
db.execute(Statement::from_string(
db.get_database_backend(),
sql.to_owned(),
))
.await
.map(|_| ())
}
#[tokio::test]
#[ignore = "requires a live Postgres (set DATABASE_URL); run with -- --ignored"]
async fn pg_constraint_name_identity_match() {
let url = pg_url();
let db = Database::connect(&url)
.await
.unwrap_or_else(|e| panic!("connect to Postgres at {url}: {e}"));
exec(&db, "DROP TABLE IF EXISTS cw_pg_gate")
.await
.expect("drop");
exec(
&db,
"CREATE TABLE cw_pg_gate (id INT PRIMARY KEY, slug TEXT NOT NULL, \
CONSTRAINT cw_pg_slug_key UNIQUE (slug))",
)
.await
.expect("create table with named unique constraint");
exec(&db, "INSERT INTO cw_pg_gate (id, slug) VALUES (1, 'taken')")
.await
.expect("seed winning insert");
let err = exec(&db, "INSERT INTO cw_pg_gate (id, slug) VALUES (2, 'taken')")
.await
.expect_err("expected a UNIQUE violation from the losing insert");
let map = ConstraintMap::new().on("cw_pg_slug_key", "slug", "has already been taken");
let ve = map
.try_map(err)
.expect("try_map should match the Postgres constraint name and return ValidationError");
assert!(
ve.has("slug"),
"expected a field error on 'slug' from the Postgres constraint() path, got: {ve:?}"
);
let _ = exec(&db, "DROP TABLE IF EXISTS cw_pg_gate").await;
}