Skip to main content

wae_database/orm/
entity.rs

1//! 实体定义模块
2//!
3//! 提供实体与数据库表的映射关系定义
4
5use crate::{
6    DatabaseResult,
7    connection::{DatabaseRow, FromDatabaseValue},
8};
9use wae_types::Value;
10
11/// 数据库实体 trait
12///
13/// 定义实体与数据库表的映射关系
14///
15/// # Example
16///
17/// ```ignore
18/// struct User {
19///     id: i64,
20///     name: String,
21///     email: String,
22/// }
23///
24/// impl Entity for User {
25///     type Id = i64;
26///
27///     fn table_name() -> &'static str {
28///         "users"
29///     }
30///
31///     fn id(&self) -> Self::Id {
32///         self.id
33///     }
34/// }
35/// ```
36pub trait Entity: Sized + Send + Sync + 'static {
37    /// 主键类型
38    type Id: FromDatabaseValue + Into<Value> + Send + Sync + Clone;
39
40    /// 表名
41    fn table_name() -> &'static str;
42
43    /// 获取主键值
44    fn id(&self) -> Self::Id;
45
46    /// 主键列名,默认为 "id"
47    fn id_column() -> &'static str {
48        "id"
49    }
50}
51
52/// 从数据库行解析实体
53pub trait FromRow: Sized {
54    /// 从数据库行解析
55    fn from_row(row: &DatabaseRow) -> DatabaseResult<Self>;
56}
57
58/// 将实体转换为数据库行
59pub trait ToRow {
60    /// 转换为列名和值的列表
61    fn to_row(&self) -> Vec<(&'static str, Value)>;
62}