Skip to main content

TableConfig

Struct TableConfig 

Source
#[non_exhaustive]
pub struct TableConfig { pub table_name: String, pub display_name: String, pub primary_key: String, pub fields: HashMap<String, FieldConfig>, pub unique_indexes: Vec<IndexConfig>, pub indexes: Vec<IndexConfig>, pub default_order: Vec<(String, SortOrder)>, pub soft_delete_field: Option<String>, pub timestamp_fields: Option<TimestampFields>, }
Expand description

表配置

定义数据表的完整配置,包括:

  • 表名和显示名称
  • 主键字段
  • 字段列表
  • 索引配置(唯一索引、普通索引)
  • 默认排序规则
  • 软删除字段
  • 时间戳字段配置

§示例

use yang_base::table::{TableConfig, FieldConfig, FieldType, SortOrder};

// 创建一个用户表配置
let table = TableConfig::new("users")
    .display_name("用户表")
    .primary_key("id")
    .field(FieldConfig::new("id", FieldType::BigInt).required(true)).expect("有效字段配置应注册成功")
    .field(FieldConfig::new("username", FieldType::String { max_length: 50 }).required(true)).expect("有效字段配置应注册成功")
    .field(FieldConfig::new("email", FieldType::String { max_length: 100 }).required(true)).expect("有效字段配置应注册成功")
    .unique_index(vec!["username".to_string()])
    .unique_index(vec!["email".to_string()])
    .default_order(vec![("created_at".to_string(), SortOrder::Desc)])
    .soft_delete_field("deleted_at")
    .timestamps(true, true, true);

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§table_name: String

表名

数据库中的表名称,通常使用蛇形命名法(snake_case)

§display_name: String

显示名称

用于前端展示的表名称,通常使用中文

§primary_key: String

主键字段名

表的主键字段,通常为 “id”

§fields: HashMap<String, FieldConfig>

字段配置列表

使用 HashMap 存储字段配置,键为字段名,值为字段配置

§unique_indexes: Vec<IndexConfig>

唯一索引配置列表

每个唯一索引由一个或多个字段组成

§indexes: Vec<IndexConfig>

普通索引配置列表

每个普通索引由一个或多个字段组成

§default_order: Vec<(String, SortOrder)>

默认排序规则

定义查询时的默认排序字段和排序方向

§soft_delete_field: Option<String>

软删除字段名

如果设置了软删除字段,删除操作将更新该字段而非物理删除记录

§timestamp_fields: Option<TimestampFields>

时间戳字段配置

定义创建时间、更新时间和删除时间字段

Implementations§

Source§

impl TableConfig

Source

pub fn validate_schema( &self, columns: &[SchemaColumn], ) -> SchemaValidationReport

验证声明字段能否由给定数据库列提供。

这是只读、单向的运行期兼容检查:数据库额外列、索引、默认值、触发器等不属于 TableConfig 的所有权范围,因此不会作为问题,也不会生成 ALTER/回滚 SQL。

Source§

impl TableConfig

Source

pub fn new(table_name: impl Into<String>) -> Self

创建新的表配置

§参数
  • table_name: 表名
§返回值

返回一个新的 TableConfig 实例,使用默认配置

§示例
use yang_base::table::TableConfig;

let table = TableConfig::new("users");
assert_eq!(table.table_name, "users");
assert_eq!(table.primary_key, "id");
Source

pub fn display_name(self, name: impl Into<String>) -> Self

设置显示名称

§参数
  • name: 显示名称
§返回值

返回 Result<Self, BaseError>,支持通过 ? 或 expect 继续链式调用

§错误
  • BaseError::ConfigError:字段名为空白字符串
§示例
use yang_base::table::TableConfig;

let table = TableConfig::new("users")
    .display_name("用户表");
assert_eq!(table.display_name, "用户表");
Source

pub fn primary_key(self, key: impl Into<String>) -> Self

设置主键字段

§参数
  • key: 主键字段名
§返回值

返回 self,支持链式调用

§示例
use yang_base::table::TableConfig;

let table = TableConfig::new("users")
    .primary_key("user_id");
assert_eq!(table.primary_key, "user_id");
Source

pub fn field(self, field: FieldConfig) -> Result<Self, BaseError>

添加字段配置

§参数
  • field: 字段配置
§返回值

返回 self,支持链式调用

§示例
use yang_base::table::{TableConfig, FieldConfig, FieldType};

let table = TableConfig::new("users")
    .field(FieldConfig::new("id", FieldType::BigInt)).expect("有效字段配置应注册成功")
    .field(FieldConfig::new("username", FieldType::String { max_length: 50 })).expect("有效字段配置应注册成功");
assert_eq!(table.fields.len(), 2);
Source

pub fn fields(self, fields: Vec<FieldConfig>) -> Result<Self, BaseError>

批量添加字段配置

§参数
  • fields: 字段配置列表
§返回值

返回 Result<Self, BaseError>,支持通过 ? 或 expect 继续链式调用

§错误
  • BaseError::ConfigError:任一字段名为空白字符串
§示例
use yang_base::table::{TableConfig, FieldConfig, FieldType};

let table = TableConfig::new("users")
    .fields(vec![
        FieldConfig::new("id", FieldType::BigInt).required(true),
        FieldConfig::new("username", FieldType::String { max_length: 50 }).required(true),
        FieldConfig::new("email", FieldType::String { max_length: 100 }).required(true),
    ]).expect("有效字段配置应注册成功");
assert_eq!(table.fields.len(), 3);
Source

pub fn fields_from_iter<I>(self, fields: I) -> Result<Self, BaseError>
where I: IntoIterator<Item = FieldConfig>,

从迭代器批量添加字段配置

§参数
  • fields: 字段配置迭代器
§返回值

返回 Result<Self, BaseError>,支持通过 ? 或 expect 继续链式调用

§错误
  • BaseError::ConfigError:任一字段名为空白字符串
§示例
use yang_base::table::{TableConfig, FieldConfig, FieldType};

let field_configs = vec![
    FieldConfig::new("id", FieldType::BigInt),
    FieldConfig::new("username", FieldType::String { max_length: 50 }),
];

let table = TableConfig::new("users")
    .fields_from_iter(field_configs.into_iter()).expect("有效字段配置应注册成功");
assert_eq!(table.fields.len(), 2);
Source

pub fn unique_index(self, fields: Vec<String>) -> Self

添加唯一索引

§参数
  • fields: 索引字段列表
§返回值

返回 self,支持链式调用

§示例
use yang_base::table::TableConfig;

let table = TableConfig::new("users")
    .unique_index(vec!["username".to_string()])
    .unique_index(vec!["email".to_string()]);
assert_eq!(table.unique_indexes.len(), 2);
Source

pub fn index(self, fields: Vec<String>) -> Self

添加普通索引

§参数
  • fields: 索引字段列表
§返回值

返回 self,支持链式调用

§示例
use yang_base::table::TableConfig;

let table = TableConfig::new("users")
    .index(vec!["created_at".to_string()])
    .index(vec!["status".to_string(), "created_at".to_string()]);
assert_eq!(table.indexes.len(), 2);
Source

pub fn default_order(self, order: Vec<(String, SortOrder)>) -> Self

设置默认排序规则

§参数
  • order: 排序规则列表,每项为 (字段名, 排序方向)
§返回值

返回 self,支持链式调用

§示例
use yang_base::table::{TableConfig, SortOrder};

let table = TableConfig::new("users")
    .default_order(vec![
        ("created_at".to_string(), SortOrder::Desc),
        ("id".to_string(), SortOrder::Asc),
    ]);
assert_eq!(table.default_order.len(), 2);
Source

pub fn soft_delete_field(self, field: impl Into<String>) -> Self

设置软删除字段

§参数
  • field: 软删除字段名
§返回值

返回 self,支持链式调用

§示例
use yang_base::table::TableConfig;

let table = TableConfig::new("users")
    .soft_delete_field("deleted_at");
assert_eq!(table.soft_delete_field, Some("deleted_at".to_string()));
Source

pub fn timestamps( self, created_at: bool, updated_at: bool, deleted_at: bool, ) -> Self

设置时间戳字段配置

§参数
  • created_at: 是否启用创建时间字段
  • updated_at: 是否启用更新时间字段
  • deleted_at: 是否启用删除时间字段
§返回值

返回 self,支持链式调用

§示例
use yang_base::table::TableConfig;

let table = TableConfig::new("users")
    .timestamps(true, true, true);
assert!(table.timestamp_fields.is_some());
Source

pub fn validate_field(&self, field_name: &str) -> Result<(), BaseError>

验证字段是否存在

§参数
  • field_name: 字段名
§返回值

如果字段存在返回 Ok(()),否则返回 FieldNotFound 错误

§示例
use yang_base::table::{TableConfig, FieldConfig, FieldType};

let table = TableConfig::new("users")
    .field(FieldConfig::new("username", FieldType::String { max_length: 50 })).expect("有效字段配置应注册成功");

assert!(table.validate_field("username").is_ok());
assert!(table.validate_field("nonexistent").is_err());
Source

pub fn get_field(&self, field_name: &str) -> Option<&FieldConfig>

获取字段配置

§参数
  • field_name: 字段名
§返回值

如果字段存在返回字段配置的引用,否则返回 None

§示例
use yang_base::table::{TableConfig, FieldConfig, FieldType};

let table = TableConfig::new("users")
    .field(FieldConfig::new("username", FieldType::String { max_length: 50 })).expect("有效字段配置应注册成功");

let field = table.get_field("username");
assert!(field.is_some());
assert_eq!(field.unwrap().name, "username");
Source

pub fn validate_query(&self, field_names: &[&str]) -> Result<(), BaseError>

验证查询参数

验证查询中引用的所有字段是否存在于表配置中

§参数
  • field_names: 字段名列表
§返回值

如果所有字段都存在返回 Ok(()),否则返回第一个不存在的字段的错误

§示例
use yang_base::table::{TableConfig, FieldConfig, FieldType};

let table = TableConfig::new("users")
    .field(FieldConfig::new("username", FieldType::String { max_length: 50 })).expect("有效字段配置应注册成功")
    .field(FieldConfig::new("email", FieldType::String { max_length: 100 })).expect("有效字段配置应注册成功");

assert!(table.validate_query(&["username", "email"]).is_ok());
assert!(table.validate_query(&["username", "nonexistent"]).is_err());

Trait Implementations§

Source§

impl Clone for TableConfig

Source§

fn clone(&self) -> TableConfig

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for TableConfig

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more