sea-orm: Panic in `insert_many` if `ActiveModels` have different columns set

Description

insert_many panics with the message “columns mismatch” if the entities to be stored have values in a mix of columns.

Steps to Reproduce

See minimal reproduction below

Expected Behavior

This seems like it should be supported or explicitly disallowed.

Actual Behavior

Panic internal to the library

Reproduces How Often

100%

Versions

Tested with 0.10.7. Reproduces on Windows 10 and Ubuntu 20.04.

Additional Information

Minimal reproduction:

// Cargo.toml:
// [package]
// name = "sql-repr"
// version = "0.1.0"
// edition = "2021"
//
// [dependencies]
// sea-orm = { version = "0.10.7", default-features = false, features = [
//     "sqlx-sqlite",
//     "runtime-tokio-rustls",
//     "with-time",
// ] }
// sea-orm-migration = "0.10.7"
// tokio = { version = "1.23.0", features = ["full"] }
//
// [profile.dev]
// panic = "abort"

use migration::Migrator;
use sea_orm::*;
use sea_orm_migration::MigratorTrait;

mod entity {
    use super::*;
    pub mod varies {
        use super::*;

        #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, DeriveEntityModel)]
        #[sea_orm(table_name = "varies")]
        pub struct Model {
            #[sea_orm(primary_key)]
            pub id: i32,
            pub a: Option<i32>,
            pub b: Option<String>,
        }

        impl ActiveModelBehavior for ActiveModel {}

        #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
        pub enum Relation {}
    }
}

mod migration {
    use sea_orm_migration::prelude::*;

    pub struct Migrator;
    #[async_trait::async_trait]
    impl MigratorTrait for Migrator {
        fn migrations() -> Vec<Box<dyn MigrationTrait>> {
            vec![Box::new(Create)]
        }
    }

    #[derive(DeriveMigrationName)]
    struct Create;

    #[async_trait::async_trait]
    impl MigrationTrait for Create {
        async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
            manager
                .create_table(
                    Table::create()
                        .table(Varies::Table)
                        .if_not_exists()
                        .col(
                            ColumnDef::new(Varies::Id)
                                .integer()
                                .not_null()
                                .auto_increment()
                                .primary_key(),
                        )
                        .col(ColumnDef::new(Varies::A).integer().null())
                        .col(ColumnDef::new(Varies::B).string().null())
                        .to_owned(),
                )
                .await?;
            Ok(())
        }

        async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
            todo!();
        }
    }

    #[derive(Iden)]
    enum Varies {
        Table,
        Id,
        A,
        B,
    }
}

#[tokio::main]
async fn main() {
    let db = Database::connect("sqlite::memory:").await.unwrap();
    Migrator::up(&db, None).await.unwrap();

    let multi = vec![
        entity::varies::ActiveModel {
            id: ActiveValue::NotSet,
            a: ActiveValue::Set(Some(100)),
            b: ActiveValue::NotSet,
        },
        entity::varies::ActiveModel {
            id: ActiveValue::NotSet,
            a: ActiveValue::NotSet,
            b: ActiveValue::Set(Some(String::from("word"))),
        },
    ];
    entity::varies::Entity::insert_many(multi) // <- panics internally
        .exec(&db)
        .await
        .unwrap();
}

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 3
  • Comments: 16 (9 by maintainers)

Commits related to this issue

Most upvoted comments

I’ve recently bumped into this problem. While it’s not clear how sea-orm should properly solve this issue, I believe it might be useful to mention this behaviour in the docs.

- id: 1
  something: some value
  nullable1: value
- id: 2
  something: some value
  nullable2: value

It works as I expect using my sample data via loco-rs 0.9.0.

  • Data is inserted to my table with null values
  • No panic occurs

A work-around was added to loco-rs as https://github.com/loco-rs/loco/pull/845 that is marked as part of milestone https://github.com/loco-rs/loco/milestone/21

Procedure

  1. update cargo.toml to include the override
  2. run cargo update
  3. modify sample data to remove fields that are nullable and should have null values
  4. run tests.

cargo.toml override

[patch.crates-io]
sea-orm = { git = "https://github.com/SeaQL/sea-orm/", branch = "insert-no-panic"  }

package.lock entries

[[package]]
name = "sea-orm"
version = "1.1.2"
source = "git+https://github.com/SeaQL/sea-orm/?branch=insert-no-panic#cd345512031ddf813361a0bd98501553f914b0f8"

...

[[package]]
name = "loco-rs"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"

we haven’t released it yet, so to try out one has to point the dependency in cargo to something like:

sea-orm = { git = "https://github.com/SeaQL/sea-orm/", branch = "insert-no-panic"}

Dear all who are interested in this issue, I’ve made a fix in the PR 2433. It is slightly tricky, so I’d appreciate if someone can help reading / testing it!

@CandleCandle @belyakov-am @jryio