use super::{ActionRef, FieldKind, FieldName, FieldRef, TableName, WidgetHint};
use crate::datasource::DatasourceId;
use crate::error::BaseError;
use crate::table::{Field, RelationType, Table as SchemaTable, TableDefinition, Validator};
use serde_json::Value;
use std::collections::BTreeSet;
use std::marker::PhantomData;
use std::sync::Arc;
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct StorageSpec {
pub required: bool,
pub max_length: Option<usize>,
pub precision: Option<u8>,
pub scale: Option<u8>,
pub default: Option<Value>,
pub unique: bool,
pub indexed: bool,
pub renamed_from: Option<String>,
pub native_enum: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ValidationSpec {
pub min_length: Option<usize>,
pub max_length: Option<usize>,
pub minimum: Option<String>,
pub maximum: Option<String>,
pub pattern: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AccessRule {
Everyone,
Nobody,
Roles(Vec<String>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccessSpec {
pub readable: AccessRule,
pub writable: AccessRule,
pub searchable: bool,
pub filterable: bool,
pub sortable: bool,
pub secret: bool,
}
impl Default for AccessSpec {
fn default() -> Self {
Self {
readable: AccessRule::Everyone,
writable: AccessRule::Everyone,
searchable: false,
filterable: false,
sortable: false,
secret: false,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct PresentationSpec {
pub title: String,
pub description: String,
pub display: Vec<FieldRef>,
pub widget: Option<WidgetHint>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimestampMode {
Value,
CreatedAt,
UpdatedAt,
SoftDelete,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldSpec {
pub name: FieldName,
pub kind: FieldKind,
pub storage: StorageSpec,
pub validation: ValidationSpec,
pub access: AccessSpec,
pub presentation: PresentationSpec,
pub relation: Option<FieldRef>,
pub select: Option<ActionRef>,
pub options: Vec<(String, String)>,
pub timestamp_mode: TimestampMode,
pub tenant_key: bool,
}
impl FieldSpec {
pub fn new(name: FieldName, kind: FieldKind) -> Self {
Self {
name,
kind,
storage: StorageSpec::default(),
validation: ValidationSpec::default(),
access: AccessSpec::default(),
presentation: PresentationSpec::default(),
relation: None,
select: None,
options: Vec::new(),
timestamp_mode: TimestampMode::Value,
tenant_key: false,
}
}
pub fn required(mut self, required: bool) -> Self {
self.storage.required = required;
self
}
pub fn is_required(&self) -> bool {
self.storage.required
}
pub fn relation(mut self, target: FieldRef) -> Self {
self.relation = Some(target);
self
}
pub fn select(mut self, action: ActionRef) -> Self {
self.select = Some(action);
self
}
pub fn tenant_key(mut self, tenant_key: bool) -> Self {
self.tenant_key = tenant_key;
self
}
pub fn widget_hint(&self) -> WidgetHint {
if let Some(widget) = self.presentation.widget {
return widget;
}
match self.kind {
FieldKind::Key | FieldKind::Int => WidgetHint::Integer,
FieldKind::Str if self.access.secret => WidgetHint::Password,
FieldKind::Str => WidgetHint::Text,
FieldKind::Text => WidgetHint::Textarea,
FieldKind::Decimal => WidgetHint::Decimal,
FieldKind::Switch => WidgetHint::Switch,
FieldKind::Radio => WidgetHint::Radio,
FieldKind::Table => WidgetHint::RelationSelect,
FieldKind::Tree => WidgetHint::TreeSelect,
FieldKind::Timestamp => WidgetHint::DateTime,
}
}
fn into_schema_field(self) -> Result<Field, BaseError> {
let name = self.name.to_string();
let mut field = match self.kind {
FieldKind::Key => Field::id(name),
FieldKind::Str => Field::string(name, self.storage.max_length.unwrap_or(255)),
FieldKind::Text => Field::text(name),
FieldKind::Int => Field::bigint(name),
FieldKind::Decimal => Field::decimal(
name,
self.storage.precision.unwrap_or(18),
self.storage.scale.unwrap_or(2),
),
FieldKind::Switch => Field::boolean(name),
FieldKind::Radio => {
let values = self
.options
.iter()
.map(|(value, _)| value.clone())
.collect::<Vec<_>>();
if self.storage.native_enum.is_some() && self.storage.max_length.is_some() {
return Err(BaseError::ConfigError(format!(
"Radio 字段 {name} 不能同时声明 native_enum 与 varchar 存储"
)));
}
if let Some(max_length) = self.storage.max_length {
let unique = values.iter().collect::<BTreeSet<_>>();
let longest = values
.iter()
.map(|value| value.chars().count())
.max()
.unwrap_or(0);
if values.is_empty() || unique.len() != values.len() || longest > max_length {
return Err(BaseError::ConfigError(format!(
"VARCHAR Radio 字段 {name} 必须提供非空、不重复且不超过 {max_length} 字符的候选值"
)));
}
let allowed = Arc::new(values);
Field::string(name, max_length).validator(Validator::Custom(Arc::new(
move |field_name, value| match value.as_str() {
Some(value) if allowed.iter().any(|candidate| candidate == value) => {
Ok(())
}
Some(value) => Err(BaseError::InvalidEnumValue(
field_name.to_string(),
value.to_string(),
)),
None => Err(BaseError::InvalidFieldType(
field_name.to_string(),
"期望字符串类型的枚举值".to_string(),
)),
},
)))
} else {
let field = Field::enumeration(name, values);
match self.storage.native_enum {
Some(type_name) => field.native_enum(type_name),
None => field,
}
}
}
FieldKind::Table | FieldKind::Tree => Field::bigint(name),
FieldKind::Timestamp => match self.timestamp_mode {
TimestampMode::Value => Field::timestamp(name),
TimestampMode::CreatedAt => Field::created_at(name),
TimestampMode::UpdatedAt => Field::updated_at(name),
TimestampMode::SoftDelete => Field::soft_delete(name),
},
};
if self.kind != FieldKind::Key && self.storage.required {
field = field.required();
}
if let Some(default) = self.storage.default {
field = field.default(default);
}
if self.storage.unique {
field = field.unique();
}
if self.storage.indexed {
field = field.index();
}
if let Some(legacy_name) = self.storage.renamed_from {
field = field.renamed_from(legacy_name);
}
if let Some(value) = self.validation.min_length {
field = field.min_length(value);
}
if let Some(value) = self.validation.max_length {
field = field.max_length(value);
}
if let Some(pattern) = self.validation.pattern {
field = field.regex(pattern);
}
if let Some(value) = self.validation.minimum.as_deref() {
field = field.min(parse_numeric_bound(self.name.as_str(), "minimum", value)?);
}
if let Some(value) = self.validation.maximum.as_deref() {
field = field.max(parse_numeric_bound(self.name.as_str(), "maximum", value)?);
}
if self.access.secret {
field = field.secret();
}
field = apply_read_rule(field, self.access.readable);
let managed_write_default = self.access.writable == AccessRule::Everyone
&& (self.kind == FieldKind::Key
|| (self.kind == FieldKind::Timestamp
&& self.timestamp_mode != TimestampMode::Value));
field = apply_write_rule(field, self.access.writable);
if managed_write_default {
field = field.not_writable();
}
if self.access.searchable {
field = field.searchable();
}
if self.access.filterable {
field = field.filterable();
} else {
field = field.not_filterable();
}
if self.access.sortable {
field = field.sortable();
} else {
field = field.not_sortable();
}
if self.tenant_key {
field = field.tenant_key();
}
if !self.presentation.title.is_empty() {
field = field.label(self.presentation.title);
}
if let Some(target) = self.relation {
let relation_type = if self.kind == FieldKind::Tree {
RelationType::OneToMany
} else {
RelationType::ManyToOne
};
field = field.relation(
target.table().to_string(),
target.field().to_string(),
relation_type,
);
}
Ok(field)
}
}
fn apply_read_rule(field: Field, rule: AccessRule) -> Field {
match rule {
AccessRule::Everyone => field.readable(),
AccessRule::Nobody => field.not_readable(),
AccessRule::Roles(roles) => field.readable_by(roles),
}
}
fn apply_write_rule(field: Field, rule: AccessRule) -> Field {
match rule {
AccessRule::Everyone => field.writable(),
AccessRule::Nobody => field.not_writable(),
AccessRule::Roles(roles) => field.writable_by(roles),
}
}
fn parse_numeric_bound(name: &str, label: &str, raw: &str) -> Result<f64, BaseError> {
let parsed = raw.trim().parse::<f64>().map_err(|_| {
BaseError::ConfigError(format!("字段 {name} 的 {label} 必须是十进制数值: {raw:?}"))
})?;
if !parsed.is_finite() {
return Err(BaseError::ConfigError(format!(
"字段 {name} 的 {label} 必须是有限数值"
)));
}
Ok(parsed)
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Fields(Vec<FieldSpec>);
impl Fields {
pub const fn new() -> Self {
Self(Vec::new())
}
pub fn field<B>(mut self, name: FieldName, builder: B) -> Self
where
B: IntoFieldSpec,
{
self.0.push(builder.into_field_spec(name));
self
}
pub fn as_slice(&self) -> &[FieldSpec] {
&self.0
}
pub(crate) fn into_vec(self) -> Vec<FieldSpec> {
self.0
}
}
pub trait IntoFieldSpec {
fn into_field_spec(self, name: FieldName) -> FieldSpec;
}
#[derive(Debug, Clone)]
struct FieldBuilder {
kind: FieldKind,
storage: StorageSpec,
validation: ValidationSpec,
access: AccessSpec,
presentation: PresentationSpec,
relation: Option<FieldRef>,
select: Option<ActionRef>,
options: Vec<(String, String)>,
timestamp_mode: TimestampMode,
tenant_key: bool,
}
impl FieldBuilder {
fn new(kind: FieldKind) -> Self {
Self {
kind,
storage: StorageSpec::default(),
validation: ValidationSpec::default(),
access: AccessSpec::default(),
presentation: PresentationSpec::default(),
relation: None,
select: None,
options: Vec::new(),
timestamp_mode: TimestampMode::Value,
tenant_key: false,
}
}
fn build(self, name: FieldName) -> FieldSpec {
FieldSpec {
name,
kind: self.kind,
storage: self.storage,
validation: self.validation,
access: self.access,
presentation: self.presentation,
relation: self.relation,
select: self.select,
options: self.options,
timestamp_mode: self.timestamp_mode,
tenant_key: self.tenant_key,
}
}
}
macro_rules! simple_builder {
($name:ident, $kind:expr) => {
#[doc = concat!(stringify!($name), " 字段 Builder。")]
#[derive(Debug, Clone)]
pub struct $name(FieldBuilder);
impl Default for $name {
fn default() -> Self {
Self::new()
}
}
impl $name {
pub fn new() -> Self {
Self(FieldBuilder::new($kind))
}
pub fn title(mut self, value: impl Into<String>) -> Self {
self.0.presentation.title = value.into();
self
}
pub fn description(mut self, value: impl Into<String>) -> Self {
self.0.presentation.description = value.into();
self
}
pub fn widget(mut self, value: WidgetHint) -> Self {
self.0.presentation.widget = Some(value);
self
}
pub fn require(mut self, value: bool) -> Self {
self.0.storage.required = value;
self
}
pub fn default(mut self, value: impl Into<Value>) -> Self {
self.0.storage.default = Some(value.into());
self
}
pub fn unique(mut self, value: bool) -> Self {
self.0.storage.unique = value;
self
}
pub fn indexed(mut self, value: bool) -> Self {
self.0.storage.indexed = value;
self
}
pub fn renamed_from(mut self, legacy_name: impl Into<String>) -> Self {
self.0.storage.renamed_from = Some(legacy_name.into());
self
}
pub fn searchable(mut self, value: bool) -> Self {
self.0.access.searchable = value;
self
}
pub fn filterable(mut self, value: bool) -> Self {
self.0.access.filterable = value;
self
}
pub fn sortable(mut self, value: bool) -> Self {
self.0.access.sortable = value;
self
}
pub fn secret(mut self, value: bool) -> Self {
self.0.access.secret = value;
if value {
self.0.access.readable = AccessRule::Nobody;
self.0.access.writable = AccessRule::Nobody;
}
self
}
pub fn readable(mut self, value: bool) -> Self {
self.0.access.readable = if value {
AccessRule::Everyone
} else {
AccessRule::Nobody
};
self
}
pub fn readable_by<I, S>(mut self, roles: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.0.access.readable =
AccessRule::Roles(roles.into_iter().map(Into::into).collect());
self
}
pub fn writable_by<I, S>(mut self, roles: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.0.access.writable =
AccessRule::Roles(roles.into_iter().map(Into::into).collect());
self
}
pub fn tenant_key(mut self, value: bool) -> Self {
self.0.tenant_key = value;
self
}
}
impl IntoFieldSpec for $name {
fn into_field_spec(self, name: FieldName) -> FieldSpec {
self.0.build(name)
}
}
};
}
simple_builder!(Key, FieldKind::Key);
simple_builder!(Str, FieldKind::Str);
simple_builder!(Text, FieldKind::Text);
simple_builder!(Int, FieldKind::Int);
simple_builder!(Decimal, FieldKind::Decimal);
simple_builder!(Switch, FieldKind::Switch);
simple_builder!(Table, FieldKind::Table);
simple_builder!(Tree, FieldKind::Tree);
simple_builder!(Timestamp, FieldKind::Timestamp);
#[derive(Debug, Clone)]
pub struct Password(FieldBuilder);
impl Default for Password {
fn default() -> Self {
Self::new()
}
}
impl Password {
pub fn new() -> Self {
let mut inner = FieldBuilder::new(FieldKind::Str);
inner.access.secret = true;
inner.access.readable = AccessRule::Nobody;
inner.presentation.widget = Some(WidgetHint::Password);
Self(inner)
}
pub fn title(mut self, value: impl Into<String>) -> Self {
self.0.presentation.title = value.into();
self
}
pub fn widget(mut self, value: WidgetHint) -> Self {
self.0.presentation.widget = Some(value);
self
}
pub fn require(mut self, value: bool) -> Self {
self.0.storage.required = value;
self
}
pub fn min_length(mut self, value: usize) -> Self {
self.0.validation.min_length = Some(value);
self
}
pub fn max_length(mut self, value: usize) -> Self {
self.0.storage.max_length = Some(value);
self.0.validation.max_length = Some(value);
self
}
}
impl IntoFieldSpec for Password {
fn into_field_spec(self, name: FieldName) -> FieldSpec {
self.0.build(name)
}
}
impl Str {
pub fn max_length(mut self, value: usize) -> Self {
self.0.storage.max_length = Some(value);
self.0.validation.max_length = Some(value);
self
}
pub fn min_length(mut self, value: usize) -> Self {
self.0.validation.min_length = Some(value);
self
}
pub fn pattern(mut self, value: impl Into<String>) -> Self {
self.0.validation.pattern = Some(value.into());
self
}
pub fn email(mut self) -> Self {
self.0.validation.pattern =
Some(r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$".to_string());
self.0.presentation.widget = Some(WidgetHint::Email);
self
}
}
impl Decimal {
pub fn precision(mut self, precision: u8, scale: u8) -> Self {
self.0.storage.precision = Some(precision);
self.0.storage.scale = Some(scale);
self
}
}
impl Timestamp {
pub fn created_at(mut self) -> Self {
self.0.timestamp_mode = TimestampMode::CreatedAt;
self
}
pub fn updated_at(mut self) -> Self {
self.0.timestamp_mode = TimestampMode::UpdatedAt;
self
}
pub fn soft_delete(mut self) -> Self {
self.0.timestamp_mode = TimestampMode::SoftDelete;
self
}
}
macro_rules! relation_builder {
($name:ident) => {
impl $name {
pub fn target(mut self, value: FieldRef) -> Self {
self.0.relation = Some(value);
self
}
pub fn select(mut self, value: ActionRef) -> Self {
self.0.select = Some(value);
self
}
pub fn display<I>(mut self, values: I) -> Self
where
I: IntoIterator<Item = FieldRef>,
{
self.0.presentation.display = values.into_iter().collect();
self
}
}
};
}
relation_builder!(Table);
relation_builder!(Tree);
#[derive(Debug, Clone)]
pub struct Radio<T> {
inner: FieldBuilder,
marker: PhantomData<fn() -> T>,
}
impl<T> Default for Radio<T> {
fn default() -> Self {
Self::new()
}
}
impl<T> Radio<T> {
pub fn new() -> Self {
Self {
inner: FieldBuilder::new(FieldKind::Radio),
marker: PhantomData,
}
}
pub fn title(mut self, value: impl Into<String>) -> Self {
self.inner.presentation.title = value.into();
self
}
pub fn widget(mut self, value: WidgetHint) -> Self {
self.inner.presentation.widget = Some(value);
self
}
pub fn require(mut self, value: bool) -> Self {
self.inner.storage.required = value;
self
}
pub fn varchar(mut self, max_length: usize) -> Self {
self.inner.storage.max_length = Some(max_length);
self
}
pub fn native_enum(mut self, type_name: impl Into<String>) -> Self {
self.inner.storage.native_enum = Some(type_name.into());
self
}
pub fn options<I, V, S>(mut self, values: I) -> Self
where
I: IntoIterator<Item = (V, S)>,
V: ToString,
S: Into<String>,
{
self.inner.options = values
.into_iter()
.map(|(value, title)| (value.to_string(), title.into()))
.collect();
self
}
pub fn default<V>(mut self, value: V) -> Self
where
V: ToString,
{
self.inner.storage.default = Some(Value::String(value.to_string()));
self
}
pub fn filterable(mut self, value: bool) -> Self {
self.inner.access.filterable = value;
self
}
pub fn sortable(mut self, value: bool) -> Self {
self.inner.access.sortable = value;
self
}
}
impl<T> IntoFieldSpec for Radio<T> {
fn into_field_spec(self, name: FieldName) -> FieldSpec {
self.inner.build(name)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TableIndexSpec {
pub name: Option<String>,
pub fields: Vec<FieldRef>,
pub expressions: Vec<String>,
pub predicate: Option<String>,
pub unique: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TableCheckSpec {
pub name: String,
pub expression: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TableForeignKeySpec {
pub name: String,
pub fields: Vec<FieldRef>,
pub referenced_fields: Vec<FieldRef>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TableOpaqueColumnSpec {
pub name: String,
pub sql_type: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TableSpec {
pub name: TableName,
pub title: String,
pub fields: Vec<FieldSpec>,
pub indexes: Vec<TableIndexSpec>,
pub checks: Vec<TableCheckSpec>,
pub foreign_keys: Vec<TableForeignKeySpec>,
pub opaque_columns: Vec<TableOpaqueColumnSpec>,
pub datasource: Option<DatasourceId>,
pub(crate) primary_key_order: Vec<String>,
}
impl TableSpec {
pub fn new(name: TableName) -> Self {
Self {
name,
title: String::new(),
fields: Vec::new(),
indexes: Vec::new(),
checks: Vec::new(),
foreign_keys: Vec::new(),
opaque_columns: Vec::new(),
datasource: None,
primary_key_order: Vec::new(),
}
}
pub fn title(mut self, value: impl Into<String>) -> Self {
self.title = value.into();
self
}
pub fn datasource(mut self, id: DatasourceId) -> Self {
self.datasource = Some(id);
self
}
pub fn fields(mut self, fields: Fields) -> Self {
self.fields = fields.into_vec();
self.primary_key_order = self
.fields
.iter()
.filter(|field| field.kind == FieldKind::Key)
.map(|field| field.name.to_string())
.collect();
self
}
#[must_use]
pub fn field(mut self, field: FieldSpec) -> Self {
if field.kind == FieldKind::Key {
self.primary_key_order.push(field.name.to_string());
}
self.fields.push(field);
self
}
pub fn unique(mut self, fields: impl IntoIterator<Item = FieldRef>) -> Self {
self.indexes.push(TableIndexSpec {
name: None,
fields: fields.into_iter().collect(),
expressions: Vec::new(),
predicate: None,
unique: true,
});
self
}
pub fn unique_named(
mut self,
name: impl Into<String>,
fields: impl IntoIterator<Item = FieldRef>,
) -> Self {
self.indexes.push(TableIndexSpec {
name: Some(name.into()),
fields: fields.into_iter().collect(),
expressions: Vec::new(),
predicate: None,
unique: true,
});
self
}
pub fn index(mut self, fields: impl IntoIterator<Item = FieldRef>) -> Self {
self.indexes.push(TableIndexSpec {
name: None,
fields: fields.into_iter().collect(),
expressions: Vec::new(),
predicate: None,
unique: false,
});
self
}
pub fn index_named(
mut self,
name: impl Into<String>,
fields: impl IntoIterator<Item = FieldRef>,
) -> Self {
self.indexes.push(TableIndexSpec {
name: Some(name.into()),
fields: fields.into_iter().collect(),
expressions: Vec::new(),
predicate: None,
unique: false,
});
self
}
pub fn partial_index(
mut self,
name: impl Into<String>,
fields: impl IntoIterator<Item = FieldRef>,
predicate: impl Into<String>,
) -> Self {
self.indexes.push(TableIndexSpec {
name: Some(name.into()),
fields: fields.into_iter().collect(),
expressions: Vec::new(),
predicate: Some(predicate.into()),
unique: false,
});
self
}
pub fn partial_unique_named(
mut self,
name: impl Into<String>,
fields: impl IntoIterator<Item = FieldRef>,
predicate: impl Into<String>,
) -> Self {
self.indexes.push(TableIndexSpec {
name: Some(name.into()),
fields: fields.into_iter().collect(),
expressions: Vec::new(),
predicate: Some(predicate.into()),
unique: true,
});
self
}
pub fn expression_index(
mut self,
name: impl Into<String>,
expressions: impl IntoIterator<Item = impl Into<String>>,
unique: bool,
) -> Self {
self.indexes.push(TableIndexSpec {
name: Some(name.into()),
fields: Vec::new(),
expressions: expressions.into_iter().map(Into::into).collect(),
predicate: None,
unique,
});
self
}
pub fn check_named(mut self, name: impl Into<String>, expression: impl Into<String>) -> Self {
self.checks.push(TableCheckSpec {
name: name.into(),
expression: expression.into(),
});
self
}
pub fn foreign_key_named(
mut self,
name: impl Into<String>,
fields: impl IntoIterator<Item = FieldRef>,
referenced_fields: impl IntoIterator<Item = FieldRef>,
) -> Self {
self.foreign_keys.push(TableForeignKeySpec {
name: name.into(),
fields: fields.into_iter().collect(),
referenced_fields: referenced_fields.into_iter().collect(),
});
self
}
pub fn opaque_column(mut self, name: impl Into<String>, sql_type: impl Into<String>) -> Self {
self.opaque_columns.push(TableOpaqueColumnSpec {
name: name.into(),
sql_type: sql_type.into(),
});
self
}
pub fn table_definition(&self) -> Result<TableDefinition, BaseError> {
let mut table = SchemaTable::new(self.name.to_string());
table = table
.datasource(self.datasource.clone().unwrap_or_default())
.primary_key_order(self.primary_key_order.clone());
for opaque in &self.opaque_columns {
table = table.opaque_column(opaque.name.clone(), opaque.sql_type.clone());
}
if !self.title.is_empty() {
table = table.label(self.title.clone());
}
for index in &self.indexes {
let fields = self.validate_index(index)?;
if !index.expressions.is_empty() || index.predicate.is_some() {
table = table.index_spec(
index.name.clone(),
fields,
index.expressions.clone(),
index.predicate.clone(),
index.unique,
false,
);
continue;
}
table = match (&index.name, index.unique) {
(Some(name), true) => table.unique_named(name.clone(), fields),
(None, true) => table.unique(fields),
(Some(name), false) => table.index_named(name.clone(), fields),
(None, false) => table.index(fields),
};
}
for check in &self.checks {
table = table.check_named(check.name.clone(), check.expression.clone());
}
for foreign_key in &self.foreign_keys {
let (columns, referenced_table, referenced_columns) =
self.validate_foreign_key(foreign_key)?;
table = table.foreign_key_named(
foreign_key.name.clone(),
columns,
referenced_table,
referenced_columns,
);
}
let fields = self
.fields
.clone()
.into_iter()
.map(FieldSpec::into_schema_field)
.collect::<Result<Vec<_>, _>>()?;
table.fields(fields).build()
}
fn validate_index(&self, index: &TableIndexSpec) -> Result<Vec<String>, BaseError> {
if index.fields.is_empty() && index.expressions.is_empty() {
return Err(BaseError::ConfigError(format!(
"表 {} 的索引至少需要一个字段或表达式",
self.name
)));
}
if !index.expressions.is_empty() && index.name.is_none() {
return Err(BaseError::ConfigError(format!(
"表 {} 的表达式索引必须显式声明名称",
self.name
)));
}
let declared = self
.fields
.iter()
.map(|field| field.name.as_str())
.collect::<BTreeSet<_>>();
let mut seen = BTreeSet::new();
let mut fields = Vec::with_capacity(index.fields.len());
for reference in &index.fields {
if reference.table() != &self.name {
return Err(BaseError::ConfigError(format!(
"表 {} 的索引不能引用其他表字段 {}",
self.name, reference
)));
}
let field = reference.field().as_str();
if !declared.contains(field) {
return Err(BaseError::ConfigError(format!(
"表 {} 的索引引用了未声明字段 {}",
self.name, field
)));
}
if !seen.insert(field) {
return Err(BaseError::ConfigError(format!(
"表 {} 的索引重复引用字段 {}",
self.name, field
)));
}
fields.push(field.to_string());
}
Ok(fields)
}
fn validate_foreign_key(
&self,
foreign_key: &TableForeignKeySpec,
) -> Result<(Vec<String>, String, Vec<String>), BaseError> {
if foreign_key.fields.is_empty()
|| foreign_key.fields.len() != foreign_key.referenced_fields.len()
{
return Err(BaseError::ConfigError(format!(
"表 {} 的外键 {} 本地字段与目标字段必须非空且数量一致",
self.name, foreign_key.name
)));
}
let declared = self
.fields
.iter()
.map(|field| field.name.as_str())
.collect::<BTreeSet<_>>();
let mut columns = Vec::with_capacity(foreign_key.fields.len());
for field in &foreign_key.fields {
if field.table() != &self.name || !declared.contains(field.field().as_str()) {
return Err(BaseError::ConfigError(format!(
"表 {} 的外键 {} 引用了未声明的本地字段 {}",
self.name, foreign_key.name, field
)));
}
columns.push(field.field().to_string());
}
let referenced_table = foreign_key.referenced_fields[0].table().clone();
if foreign_key
.referenced_fields
.iter()
.any(|field| field.table() != &referenced_table)
{
return Err(BaseError::ConfigError(format!(
"表 {} 的外键 {} 目标字段必须来自同一张表",
self.name, foreign_key.name
)));
}
Ok((
columns,
referenced_table.to_string(),
foreign_key
.referenced_fields
.iter()
.map(|field| field.field().to_string())
.collect(),
))
}
}