Skip to main content

Model

Trait Model 

Source
pub trait Model:
    Send
    + Sync
    + Sized
    + 'static {
    type PrimaryKey: Send + Sync + Debug + Display + Clone + Default;

    // Required methods
    fn table_name() -> &'static str;
    fn pk(&self) -> Self::PrimaryKey;
    fn set_pk(&mut self, pk: Self::PrimaryKey);

    // Provided methods
    fn pk_name() -> &'static str { ... }
    fn foreign_key(relation: &str) -> String { ... }
    fn timestamp_fields() -> Option<TimestampFields> { ... }
    fn soft_delete_field() -> Option<&'static str> { ... }
    fn fields() -> Vec<(&'static str, &'static str)> { ... }
}
Expand description

所有 ORM 模型必须实现的核心 trait

L-5 修复:补充示例文档

§示例

use sz_orm_core::model::Model;

#[derive(Debug, Clone, Default)]
struct User {
    id: i64,
    name: String,
}

impl Model for User {
    type PrimaryKey = i64;
    fn table_name() -> &'static str { "users" }
    fn pk(&self) -> Self::PrimaryKey { self.id }
    fn set_pk(&mut self, pk: Self::PrimaryKey) { self.id = pk; }
}

assert_eq!(User::table_name(), "users");
assert_eq!(User::pk_name(), "id");
assert_eq!(User::foreign_key("orders"), "orders_id");

Required Associated Types§

Source

type PrimaryKey: Send + Sync + Debug + Display + Clone + Default

主键类型

Required Methods§

Source

fn table_name() -> &'static str

获取该模型对应的表名

Source

fn pk(&self) -> Self::PrimaryKey

获取当前实例的主键值

Source

fn set_pk(&mut self, pk: Self::PrimaryKey)

设置当前实例的主键值

Provided Methods§

Source

fn pk_name() -> &'static str

获取主键列名(默认 id

Source

fn foreign_key(relation: &str) -> String

根据关系名推导外键名(默认 <relation>_id

M-9 说明:默认将 relation 转为小写后拼接 _id。 对于大小写敏感的列名(如 PostgreSQL 的 User_ID),业务模型应重写此方法。

Source

fn timestamp_fields() -> Option<TimestampFields>

获取自动时间戳字段配置

Source

fn soft_delete_field() -> Option<&'static str>

获取软删除字段名

Source

fn fields() -> Vec<(&'static str, &'static str)>

获取字段定义(字段名, 类型字符串),用于 OpenAPI schema 生成等

类型字符串遵循 sz-orm casts 约定: "integer" / "float" / "boolean" / "string" / "datetime" / "date" / "time" / "json" / "array" / "bytes"

默认返回空列表;需要 schema 推导的模型应重写此方法。

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§