Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

35 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

sea-orm-typed-id

Crates.io License: MIT

A Rust library that provides a macro for generating type-safe database ID types for SeaORM.

Caveat

You might not actually need this library; it’s just a macro, and you might be better off simply copying the code from src/lib.rs into your project.

Features

  • all: Enables all features
  • schema: Enables schemars::JsonSchema support
  • utoipa: Enables OpenAPI schema generation support

Installation

Add this to your Cargo.toml:

[dependencies]
sea-orm-typed-id = { version = "0.4.1", features = ["all"] }

Usage

use sea_orm_typed_id::define_id;

// The one-argument form remains backed by i32.
define_id!(CakeId);

#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "cakes")]
pub struct Cake {
    pub id: CakeId,
}

// The backing type can also be stated explicitly.
define_id!(FillingId, i64);

#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "fillings")]
pub struct Filling {
    pub id: FillingId,
}

#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "cake_fillings")]
pub struct CakeFilling {
    pub cake_id: CakeId,
    pub filling_id: FillingId,
}

define_id! supports i32 and i64 backing types. define_id!(CakeId) is equivalent to define_id!(CakeId, i32), while define_id!(CakeId, i64) maps to SeaORM's BigInteger column type.

For an auto-incrementing PostgreSQL primary key, SeaORM 2 renders BigInteger as bigint GENERATED BY DEFAULT AS IDENTITY. Enable SeaORM's postgres-use-serial-pk feature when the schema should use BIGSERIAL instead.

Known Shortcomings

Typed IDs won't work with postgres arrays.

// ...
pub struct Model {
    // ...
    pub filling_ids: Vec<FillingId>, // Doesn't work
}

This won't compile because Vec<FillingId> doesn't implement sea_orm::TryGetable which we also can't add ourselves as both Vec and sea_orm::TryGetable are external.

One of possible workouts is to make fields private and add getter for it.

// ...
pub struct Model {
    // ...
    filling_ids: Vec<i64>,
}

impl Model {
    pub fn filling_ids(&self) -> Vec<FillingId> {
        self.filling_ids.iter().map(FillingId::from).collect()
    }
}

License

This project is licensed under the MIT License. See the LICENSE file for details.

About

No description, website, or topics provided.

Resources

Stars

12 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages