expression

SeaORM: integration test for a foreign key

A disposable SQLite integration fixture checks that a nonexistent shelf cannot be assigned to a book. First verify the foreign-key setting on the same connection, then assert the failure and the unchanged count. An error alone is not proof of a particular constraint code; a real suite should also classify the database error. Uses a disposable in-memory SQLite database. Expected stdout (not executed): invalid reference rejected Common mistake: Assuming all databases use the same constraint configuration or error codes.

Formal Syntax & Structure

rust syntaxrust
assert!(insert_result.is_err());

Working Example

Example Snippetrust
use sea_orm::{ActiveModelTrait, ConnectOptions, ConnectionTrait, Database,    DatabaseConnection, DbBackend, DbErr, EntityTrait, LoaderTrait, ModelTrait,    PaginatorTrait, QueryOrder, Set, Statement, TransactionTrait};
mod shelf {    use sea_orm::entity::prelude::*;    #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]    #[sea_orm(table_name = "shelves")]    pub struct Model {        #[sea_orm(primary_key)]        pub id: i32,        pub label: String,    }    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]    pub enum Relation {        #[sea_orm(has_many = "super::book::Entity")]        Book,    }    impl Related<super::book::Entity> for Entity {        fn to() -> RelationDef { Relation::Book.def() }    }    impl ActiveModelBehavior for ActiveModel {}}mod book {    use sea_orm::entity::prelude::*;    #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]    #[sea_orm(table_name = "books")]    pub struct Model {        #[sea_orm(primary_key)]        pub id: i32,        pub shelf_id: i32,        pub title: String,    }    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]    pub enum Relation {        #[sea_orm(belongs_to = "super::shelf::Entity", from = "Column::ShelfId",                  to = "super::shelf::Column::Id")]        Shelf,    }    impl Related<super::shelf::Entity> for Entity {        fn to() -> RelationDef { Relation::Shelf.def() }    }    impl ActiveModelBehavior for ActiveModel {}}async fn empty_db() -> Result<DatabaseConnection, DbErr> {    let mut opt = ConnectOptions::new("sqlite::memory:");    opt.max_connections(1).min_connections(1).sqlx_logging(false);    Database::connect(opt).await}async fn sample_db() -> Result<DatabaseConnection, DbErr> {    let db = empty_db().await?;    for sql in [        "PRAGMA foreign_keys = ON",        "CREATE TABLE shelves (id INTEGER PRIMARY KEY, label TEXT NOT NULL)",        "CREATE TABLE books (id INTEGER PRIMARY KEY, shelf_id INTEGER NOT NULL REFERENCES shelves(id), title TEXT NOT NULL)",        "INSERT INTO shelves VALUES (1, 'Science'), (2, 'Art')",        "INSERT INTO books VALUES (1, 1, 'Stars'), (2, 1, 'Plants')",    ] {        db.execute(Statement::from_string(DbBackend::Sqlite, sql.to_owned())).await?;    }    Ok(db)}#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), DbErr> {    let db = sample_db().await?;    let setting = db.query_one(Statement::from_string(DbBackend::Sqlite, "PRAGMA foreign_keys".to_owned())).await?.expect("pragma result");    let enabled: i32 = setting.try_get("", "foreign_keys")?;    assert_eq!(enabled, 1);    let result = book::ActiveModel { shelf_id: Set(999), title: Set("Invalid".to_owned()), ..Default::default() }.insert(&db).await;    assert!(result.is_err());    assert_eq!(book::Entity::find().count(&db).await?, 2);    println!("invalid reference rejected");    Ok(())}
Rust Reference