Skip to main content

FieldConfig

Struct FieldConfig 

Source
#[non_exhaustive]
pub struct FieldConfig { pub name: String, pub display_name: String, pub field_type: FieldType, pub required: bool, pub default_value: Option<Value>, pub validators: Vec<Validator>, pub permissions: FieldPermissions, pub filterable: bool, pub sortable: bool, pub relation: Option<RelationConfig>, }
Expand description

字段配置

定义单个字段的所有属性,包括:

  • 字段名称和显示名称
  • 字段类型
  • 必填标记和默认值
  • 验证器列表
  • 字段级权限配置
  • 关联表信息

§示例

use yang_base::table::{FieldConfig, FieldType, Validator, FieldPermissions};
use serde_json::json;
use std::collections::HashSet;

// 创建一个必填的用户名字段
let username_field = FieldConfig::new("username", FieldType::String { max_length: 50 })
    .display_name("用户名")
    .required(true)
    .validator(Validator::MinLength(3))
    .validator(Validator::MaxLength(50));

// 创建一个带默认值的状态字段
let status_field = FieldConfig::new("status", FieldType::Enum {
    values: vec!["active".to_string(), "inactive".to_string()],
})
    .display_name("状态")
    .default_value(json!("active"));

// 创建一个带权限控制的邮箱字段
let email_field = FieldConfig::new("email", FieldType::String { max_length: 100 })
    .display_name("邮箱")
    .required(true)
    .validator(Validator::Email)
    .permissions(FieldPermissions {
        readable_roles: HashSet::from(["admin".to_string(), "user".to_string()]),
        writable_roles: HashSet::from(["admin".to_string()]),
        filterable_roles: HashSet::new(),
        sortable_roles: HashSet::new(),
    });

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.
§name: String

字段名

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

§display_name: String

显示名称

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

§field_type: FieldType

字段类型

定义字段的数据类型,如字符串、整数、枚举等

§required: bool

是否必填

如果为 true,则字段值不能为 null

§default_value: Option<Value>

默认值

当插入数据时未提供该字段值时使用的默认值

§validators: Vec<Validator>

验证器列表

用于验证字段值的验证器,按顺序执行

§permissions: FieldPermissions

字段权限

定义不同角色对该字段的访问权限

§filterable: bool

是否可筛选

如果为 true,则该字段可以用于 WHERE 条件筛选

§sortable: bool

是否可排序

如果为 true,则该字段可以用于 ORDER BY 排序

§relation: Option<RelationConfig>

关联表配置

用于外键字段,定义与其他表的关联关系

Implementations§

Source§

impl FieldConfig

Source

pub fn new(name: impl Into<String>, field_type: FieldType) -> Self

创建新的字段配置

§参数
  • name: 字段名称
  • field_type: 字段类型
§返回值

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

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

let field = FieldConfig::new("username", FieldType::String { max_length: 50 });
assert_eq!(field.name, "username");
assert!(!field.required);
Source

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

设置显示名称

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

返回 self,支持链式调用

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

let field = FieldConfig::new("username", FieldType::String { max_length: 50 })
    .display_name("用户名");
assert_eq!(field.display_name, "用户名");
Source

pub fn required(self, required: bool) -> Self

设置必填标记

§参数
  • required: 是否必填
§返回值

返回 self,支持链式调用

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

let field = FieldConfig::new("email", FieldType::String { max_length: 100 })
    .required(true);
assert!(field.required);
Source

pub fn default_value(self, value: Value) -> Self

设置默认值

§参数
  • value: 默认值
§返回值

返回 self,支持链式调用

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

let field = FieldConfig::new("status", FieldType::String { max_length: 20 })
    .default_value(json!("active"));
assert_eq!(field.default_value, Some(json!("active")));
Source

pub fn validator(self, validator: Validator) -> Self

添加验证器

§参数
  • validator: 验证器
§返回值

返回 self,支持链式调用

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

let field = FieldConfig::new("age", FieldType::Integer)
    .validator(Validator::Min(0.0))
    .validator(Validator::Max(150.0));
assert_eq!(field.validators.len(), 2);
Source

pub fn permissions(self, permissions: FieldPermissions) -> Self

设置字段权限

§参数
  • permissions: 字段权限配置
§返回值

返回 self,支持链式调用

§示例
use yang_base::table::{FieldConfig, FieldType, FieldPermissions};
use std::collections::HashSet;

let permissions = FieldPermissions {
    readable_roles: HashSet::from(["admin".to_string()]),
    writable_roles: HashSet::from(["admin".to_string()]),
    filterable_roles: HashSet::new(),
    sortable_roles: HashSet::new(),
};

let field = FieldConfig::new("salary", FieldType::Double)
    .permissions(permissions);
assert_eq!(field.permissions.readable_roles.len(), 1);
Source

pub fn relation(self, relation: RelationConfig) -> Self

设置关联表配置

§参数
  • relation: 关联表配置
§返回值

返回 self,支持链式调用

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

let relation = RelationConfig {
    table: "users".to_string(),
    field: "id".to_string(),
    display_fields: vec!["username".to_string(), "email".to_string()],
    relation_type: RelationType::OneToOne,
};

let field = FieldConfig::new("user_id", FieldType::BigInt)
    .relation(relation);
assert!(field.relation.is_some());
Source

pub fn filterable(self, filterable: bool) -> Self

设置是否可筛选

§参数
  • filterable: 是否可筛选
§返回值

返回 self,支持链式调用

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

let field = FieldConfig::new("password", FieldType::String { max_length: 255 })
    .filterable(false);
assert!(!field.filterable);
Source

pub fn sortable(self, sortable: bool) -> Self

设置是否可排序

§参数
  • sortable: 是否可排序
§返回值

返回 self,支持链式调用

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

let field = FieldConfig::new("description", FieldType::Text)
    .sortable(false);
assert!(!field.sortable);
Source

pub fn validate(&self, value: &Value) -> Result<(), BaseError>

验证字段值

执行完整的字段验证流程:

  1. 检查必填约束
  2. 执行字段类型验证
  3. 依次执行所有配置的验证器
§参数
  • value: 要验证的值
§返回值

如果验证通过返回 Ok(()),否则返回相应的错误

§错误
  • BaseError::FieldRequired: 字段为必填但值为 null
  • BaseError::InvalidFieldType: 字段类型验证失败
  • BaseError::ValidationFailed: 验证器验证失败
§示例
use yang_base::table::{FieldConfig, FieldType, Validator};
use serde_json::json;

let field = FieldConfig::new("username", FieldType::String { max_length: 50 })
    .required(true)
    .validator(Validator::MinLength(3));

// 验证通过
assert!(field.validate(&json!("alice")).is_ok());

// 必填字段为 null
assert!(field.validate(&json!(null)).is_err());

// 长度不足
assert!(field.validate(&json!("ab")).is_err());

Trait Implementations§

Source§

impl Clone for FieldConfig

Source§

fn clone(&self) -> FieldConfig

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 FieldConfig

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