sea-orm icon indicating copy to clipboard operation
sea-orm copied to clipboard

Allow unique key to be used instead of primary key

Open Sytten opened this issue 2 years ago • 1 comments

Motivation

Currently the primary must be specified for many operations like update to work, otherwise it panics. In reality this is unnecessarily strict since since any unique column or combination of columns would work.

Proposed Solutions

I have not been in the codebase much yet, but I feel this will require a new implementation similar to PrimaryKey, maybe we could call it SecondaryKeys and a changes in all places that currently check for only the primary key.

Current Workarounds

Use more generic methods like update_many, but then you hit the problem #1669

Sytten avatar May 25 '23 16:05 Sytten

Hey @Sytten, welcome back!! In SeaORM, we assumed each table has a "primary key", or more accurately an "unique key". SeaORM doesn't really check if the specified column / combination of column are in fact "primary key" or not. All it want is an "unique key" to identify a row from the database. So, you can safely add the "primary_key" attribute to your unique column. Or, is there anything else preventing you from doing so?

use sea_orm::entity::prelude::*;

#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "model")]
pub struct Model {
    #[sea_orm(primary_key, auto_increment = false)]
    pub id_1: i32,
    #[sea_orm(primary_key, auto_increment = false)]
    pub id_2: String,
    #[sea_orm(primary_key, auto_increment = false)]
    pub id_3: f64,
    #[sea_orm(primary_key, auto_increment = false)]
    pub id_4: Uuid,
    pub owner: String,
    pub name: String,
    pub description: String,
}

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

impl ActiveModelBehavior for ActiveModel {}

billy1624 avatar May 29 '23 13:05 billy1624