Skip to main content

yang_base/table/
definition.rs

1//! Schema-first 数据表定义。
2//!
3//! [`Table`] 与 [`Field`] 是应用侧唯一需要使用的构建器。字段名、数据库类型、
4//! 验证、权限、索引和时间戳语义在同一处声明,最终由 [`Table::build`] 一次校验并
5//! 生成不可变 [`TableDefinition`]。
6
7use super::field_config::{Audience, FieldConfig, FieldPermissions, RelationConfig, RelationType};
8use super::table_config::{
9    CheckConfig, ForeignKeyConfig, IndexConfig, OpaqueColumnConfig, TableConfig, TimestampFields,
10};
11#[cfg(any(feature = "mysql", feature = "postgres"))]
12use super::TableQuery;
13use super::{FieldType, RegexCache, SortOrder, Validator, MAX_VARCHAR_LENGTH};
14use crate::datasource::DatasourceId;
15use crate::error::BaseError;
16use serde_json::{json, Map, Value};
17use std::collections::{HashMap, HashSet};
18use std::sync::Arc;
19
20/// 创建数据库列名引用,用于表级排序和复合索引配置。
21pub fn col(name: impl Into<String>) -> ColumnName {
22    ColumnName(name.into())
23}
24
25/// 数据库列名引用。
26#[derive(Debug, Clone, PartialEq, Eq, Hash)]
27pub struct ColumnName(String);
28
29impl ColumnName {
30    /// 创建升序规则。
31    pub fn asc(self) -> Order {
32        Order {
33            field: self.0,
34            direction: SortOrder::Asc,
35        }
36    }
37
38    /// 创建降序规则。
39    pub fn desc(self) -> Order {
40        Order {
41            field: self.0,
42            direction: SortOrder::Desc,
43        }
44    }
45
46    fn into_name(self) -> String {
47        self.0
48    }
49}
50
51impl From<&str> for ColumnName {
52    fn from(value: &str) -> Self {
53        Self(value.to_string())
54    }
55}
56
57impl From<String> for ColumnName {
58    fn from(value: String) -> Self {
59        Self(value)
60    }
61}
62
63/// 表的默认排序条目。
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct Order {
66    field: String,
67    direction: SortOrder,
68}
69
70/// Schema-first 字段构建器。
71///
72/// 字段名和字段配置从构造函数开始就是一个整体,例如
73/// `Field::string("username", 64).required().unique()`。
74#[derive(Debug, Clone)]
75#[must_use = "字段定义必须传给 Table::fields"]
76pub struct Field {
77    config: FieldConfig,
78    primary_key: bool,
79    unique: bool,
80    unique_name: Option<String>,
81    index: bool,
82    index_name: Option<String>,
83    created_at: bool,
84    updated_at: bool,
85    deleted_at: bool,
86    soft_delete: bool,
87    relation_display_fields: Option<Vec<String>>,
88}
89
90impl Field {
91    fn new(name: impl Into<String>, field_type: FieldType) -> Self {
92        Self {
93            config: FieldConfig::new(name, field_type),
94            primary_key: false,
95            unique: false,
96            unique_name: None,
97            index: false,
98            index_name: None,
99            created_at: false,
100            updated_at: false,
101            deleted_at: false,
102            soft_delete: false,
103            relation_display_fields: None,
104        }
105    }
106
107    /// 声明当前字段由一个旧列原位改名而来;同步器不会复制或删除数据。
108    pub fn renamed_from(mut self, legacy_name: impl Into<String>) -> Self {
109        self.config.renamed_from = Some(legacy_name.into());
110        self
111    }
112
113    /// 声明 PostgreSQL 生成列(`GENERATED ALWAYS AS (<expr>) STORED`)。
114    ///
115    /// 表达式属于受信任的应用定义,不得来自请求或运行时配置;生成列同时会
116    /// 被标记为不可写,避免内置 CRUD 尝试写入数据库自算的值。
117    pub fn generated(mut self, expression: impl Into<String>) -> Self {
118        self.config.generated = Some(expression.into());
119        self.config.permissions.writable = Audience::Nobody;
120        self
121    }
122
123    /// 设置数据库列注释(PostgreSQL 通过 `COMMENT ON COLUMN` 同步)。
124    pub fn comment(mut self, comment: impl Into<String>) -> Self {
125        self.config.comment = Some(comment.into());
126        self
127    }
128
129    /// 设置列排序规则(PostgreSQL `COLLATE`)。
130    pub fn collation(mut self, collation: impl Into<String>) -> Self {
131        self.config.collation = Some(collation.into());
132        self
133    }
134
135    /// 声明复用 PostgreSQL 原生枚举类型(如 `order_status`)。
136    ///
137    /// 变体值仍由 [`Field::enumeration`] 声明;同步器会创建缺失的类型并补齐
138    /// 缺失的枚举值。MySQL 方言在渲染 DDL 时明确拒绝该声明。
139    pub fn native_enum(mut self, type_name: impl Into<String>) -> Self {
140        self.config.native_enum = Some(type_name.into());
141        self
142    }
143
144    /// 创建 64 位自增主键字段。
145    pub fn id(name: impl Into<String>) -> Self {
146        Self::new(name, FieldType::BigInt)
147            .required()
148            .primary_key()
149            .auto_increment()
150            .not_writable()
151    }
152
153    /// 创建定长上限字符串字段。
154    pub fn string(name: impl Into<String>, max_length: usize) -> Self {
155        Self::new(name, FieldType::String { max_length })
156    }
157
158    /// 创建 32 位整数字段。
159    pub fn integer(name: impl Into<String>) -> Self {
160        Self::new(name, FieldType::Integer)
161    }
162
163    /// 创建 64 位整数字段。
164    pub fn bigint(name: impl Into<String>) -> Self {
165        Self::new(name, FieldType::BigInt)
166    }
167
168    /// 创建 32 位浮点数字段。
169    pub fn float(name: impl Into<String>) -> Self {
170        Self::new(name, FieldType::Float)
171    }
172
173    /// 创建 64 位浮点数字段。
174    pub fn double(name: impl Into<String>) -> Self {
175        Self::new(name, FieldType::Double)
176    }
177
178    /// 创建定点小数字段。
179    pub fn decimal(name: impl Into<String>, precision: u8, scale: u8) -> Self {
180        Self::new(name, FieldType::Decimal { precision, scale })
181    }
182
183    /// 创建布尔字段。
184    pub fn boolean(name: impl Into<String>) -> Self {
185        Self::new(name, FieldType::Boolean)
186    }
187
188    /// 创建日期字段。
189    pub fn date(name: impl Into<String>) -> Self {
190        Self::new(name, FieldType::Date)
191    }
192
193    /// 创建日期时间字段。
194    pub fn datetime(name: impl Into<String>) -> Self {
195        Self::new(name, FieldType::DateTime)
196    }
197
198    /// 创建 Unix 时间戳字段。
199    pub fn timestamp(name: impl Into<String>) -> Self {
200        Self::new(name, FieldType::Timestamp)
201    }
202
203    /// 创建 JSON 字段。
204    pub fn json(name: impl Into<String>) -> Self {
205        Self::new(name, FieldType::Json)
206    }
207
208    /// 创建长文本字段。
209    pub fn text(name: impl Into<String>) -> Self {
210        Self::new(name, FieldType::Text)
211    }
212
213    /// 创建 UUID 字段(MySQL 渲染为 `CHAR(36)`,PostgreSQL 为 `uuid`)。
214    pub fn uuid(name: impl Into<String>) -> Self {
215        Self::new(name, FieldType::Uuid)
216    }
217
218    /// 创建二进制字段(运行期 Base64 字符串;MySQL `BLOB`,PostgreSQL `BYTEA`)。
219    pub fn bytes(name: impl Into<String>) -> Self {
220        Self::new(name, FieldType::Bytes)
221    }
222
223    /// 创建标量元素数组字段(仅 PostgreSQL 支持;MySQL 渲染时明确拒绝)。
224    pub fn array(name: impl Into<String>, element: FieldType) -> Self {
225        Self::new(name, FieldType::Array(Box::new(element)))
226    }
227
228    /// 创建枚举字段。
229    pub fn enumeration<I, S>(name: impl Into<String>, values: I) -> Self
230    where
231        I: IntoIterator<Item = S>,
232        S: Into<String>,
233    {
234        Self::new(
235            name,
236            FieldType::Enum {
237                values: values.into_iter().map(Into::into).collect(),
238            },
239        )
240    }
241
242    /// 创建自动写入的创建时间字段。
243    pub fn created_at(name: impl Into<String>) -> Self {
244        let mut field = Self::bigint(name).required().not_writable();
245        field.created_at = true;
246        field
247    }
248
249    /// 创建自动写入的更新时间字段。
250    pub fn updated_at(name: impl Into<String>) -> Self {
251        let mut field = Self::bigint(name).required().not_writable();
252        field.updated_at = true;
253        field
254    }
255
256    /// 创建软删除时间字段。
257    pub fn soft_delete(name: impl Into<String>) -> Self {
258        let mut field = Self::bigint(name).not_writable();
259        field.deleted_at = true;
260        field.soft_delete = true;
261        field
262    }
263
264    /// 设置展示名称。
265    pub fn label(mut self, label: impl Into<String>) -> Self {
266        self.config.display_name = label.into();
267        self
268    }
269
270    /// 设置为必填字段。
271    pub fn required(mut self) -> Self {
272        self.config.required = true;
273        self
274    }
275
276    /// 设置为可空字段。
277    pub fn nullable(mut self) -> Self {
278        self.config.required = false;
279        self
280    }
281
282    /// 设置数据库默认值。
283    pub fn default(mut self, value: impl Into<Value>) -> Self {
284        self.config.default_value = Some(value.into());
285        self
286    }
287
288    /// 设置数据库自增。
289    pub fn auto_increment(mut self) -> Self {
290        self.config.auto_increment = true;
291        self
292    }
293
294    /// 设置为主键。
295    pub fn primary_key(mut self) -> Self {
296        self.primary_key = true;
297        self
298    }
299
300    /// 添加单字段唯一索引。
301    pub fn unique(mut self) -> Self {
302        self.unique = true;
303        self
304    }
305
306    /// 添加指定名称的单字段唯一索引。
307    pub fn unique_named(mut self, name: impl Into<String>) -> Self {
308        self.unique = true;
309        self.unique_name = Some(name.into());
310        self
311    }
312
313    /// 添加单字段普通索引。
314    pub fn index(mut self) -> Self {
315        self.index = true;
316        self
317    }
318
319    /// 添加指定名称的单字段普通索引。
320    pub fn index_named(mut self, name: impl Into<String>) -> Self {
321        self.index = true;
322        self.index_name = Some(name.into());
323        self
324    }
325
326    /// 添加底层验证器。
327    pub fn validator(mut self, validator: Validator) -> Self {
328        self.config.validators.push(validator);
329        self
330    }
331
332    /// 设置字符串最小长度。
333    pub fn min_length(self, value: usize) -> Self {
334        self.validator(Validator::MinLength(value))
335    }
336
337    /// 设置字符串最大长度验证。
338    pub fn max_length(self, value: usize) -> Self {
339        self.validator(Validator::MaxLength(value))
340    }
341
342    /// 同时设置字符串最小、最大长度验证。
343    pub fn length(self, range: std::ops::RangeInclusive<usize>) -> Self {
344        self.min_length(*range.start()).max_length(*range.end())
345    }
346
347    /// 设置数值最小值验证。
348    pub fn min(self, value: f64) -> Self {
349        self.validator(Validator::Min(value))
350    }
351
352    /// 设置数值最大值验证。
353    pub fn max(self, value: f64) -> Self {
354        self.validator(Validator::Max(value))
355    }
356
357    /// 设置严格邮箱验证。
358    pub fn email(self) -> Self {
359        self.validator(Validator::Email)
360    }
361
362    /// 设置严格手机号验证。
363    pub fn phone(self) -> Self {
364        self.validator(Validator::Phone)
365    }
366
367    /// 设置 URL 验证。
368    pub fn url(self) -> Self {
369        self.validator(Validator::Url)
370    }
371
372    /// 设置正则表达式验证。
373    pub fn regex(self, pattern: impl Into<String>) -> Self {
374        self.validator(Validator::Regex(pattern.into()))
375    }
376
377    /// 允许所有角色读取。
378    pub fn readable(mut self) -> Self {
379        self.config.permissions.readable = Audience::Everyone;
380        self
381    }
382
383    /// 禁止任何角色读取。
384    pub fn not_readable(mut self) -> Self {
385        self.config.permissions.readable = Audience::Nobody;
386        self
387    }
388
389    /// 仅允许指定角色读取。
390    pub fn readable_by<I, S>(mut self, roles: I) -> Self
391    where
392        I: IntoIterator<Item = S>,
393        S: Into<String>,
394    {
395        self.config.permissions.readable = Audience::roles(roles);
396        self
397    }
398
399    /// 仅允许指定角色写入。
400    pub fn writable_by<I, S>(mut self, roles: I) -> Self
401    where
402        I: IntoIterator<Item = S>,
403        S: Into<String>,
404    {
405        self.config.permissions.writable = Audience::roles(roles);
406        self
407    }
408
409    /// 允许所有角色写入。
410    pub fn writable(mut self) -> Self {
411        self.config.permissions.writable = Audience::Everyone;
412        self
413    }
414
415    /// 禁止任何角色写入。
416    pub fn not_writable(mut self) -> Self {
417        self.config.permissions.writable = Audience::Nobody;
418        self
419    }
420
421    /// 允许字段用于关键词搜索(OR LIKE)。
422    ///
423    /// 与结构化筛选的 [`Field::filterable`] 位相互独立;只有文本字段
424    /// (`Field::string` / `Field::text`)会实际参与搜索,定义层在构建期
425    /// 会对非文本字段的 searchable 声明报错。
426    pub fn searchable(mut self) -> Self {
427        self.config.searchable = true;
428        self
429    }
430
431    /// 允许字段用于筛选。
432    pub fn filterable(mut self) -> Self {
433        self.config.filterable = true;
434        self.config.permissions.filterable = Audience::Everyone;
435        self
436    }
437
438    /// 禁止字段用于筛选。
439    pub fn not_filterable(mut self) -> Self {
440        self.config.filterable = false;
441        self.config.permissions.filterable = Audience::Nobody;
442        self
443    }
444
445    /// 仅允许指定角色使用字段筛选。
446    pub fn filterable_by<I, S>(mut self, roles: I) -> Self
447    where
448        I: IntoIterator<Item = S>,
449        S: Into<String>,
450    {
451        self.config.filterable = true;
452        self.config.permissions.filterable = Audience::roles(roles);
453        self
454    }
455
456    /// 允许字段用于排序。
457    pub fn sortable(mut self) -> Self {
458        self.config.sortable = true;
459        self.config.permissions.sortable = Audience::Everyone;
460        self
461    }
462
463    /// 禁止字段用于排序。
464    pub fn not_sortable(mut self) -> Self {
465        self.config.sortable = false;
466        self.config.permissions.sortable = Audience::Nobody;
467        self
468    }
469
470    /// 仅允许指定角色使用字段排序。
471    pub fn sortable_by<I, S>(mut self, roles: I) -> Self
472    where
473        I: IntoIterator<Item = S>,
474        S: Into<String>,
475    {
476        self.config.sortable = true;
477        self.config.permissions.sortable = Audience::roles(roles);
478        self
479    }
480
481    /// 将字段标记为租户隔离键。
482    pub fn tenant_key(mut self) -> Self {
483        self.config.tenant_key = true;
484        self
485    }
486
487    /// 设置敏感字段预设。
488    ///
489    /// 敏感字段不会进入默认 Record 投影或表 JSON Schema,并默认禁止读取、写入、
490    /// 筛选和排序。内部服务若确实需要显式读取或写入,必须随后调用
491    /// [`Field::readable_by`] / [`Field::writable_by`] 指定专用角色和显式字段列表。
492    pub fn secret(mut self) -> Self {
493        self.config.hidden = true;
494        self.config.permissions = FieldPermissions {
495            readable: Audience::Nobody,
496            writable: Audience::Nobody,
497            filterable: Audience::Nobody,
498            sortable: Audience::Nobody,
499        };
500        self.config.searchable = false;
501        self.config.filterable = false;
502        self.config.sortable = false;
503        self
504    }
505
506    /// 设置关联关系。
507    pub fn relation(
508        mut self,
509        table: impl Into<String>,
510        field: impl Into<String>,
511        relation_type: RelationType,
512    ) -> Self {
513        self.config.relation = Some(RelationConfig {
514            table: table.into(),
515            field: field.into(),
516            display_fields: Vec::new(),
517            relation_type,
518        });
519        self
520    }
521
522    /// 设置关联展示字段。
523    pub fn relation_display_fields<I, S>(mut self, fields: I) -> Self
524    where
525        I: IntoIterator<Item = S>,
526        S: Into<String>,
527    {
528        self.relation_display_fields = Some(fields.into_iter().map(Into::into).collect());
529        self
530    }
531}
532
533#[derive(Debug, Clone)]
534struct PendingIndex {
535    name: Option<String>,
536    fields: Vec<String>,
537    expressions: Vec<String>,
538    predicate: Option<String>,
539    unique: bool,
540    nulls_not_distinct: bool,
541}
542
543#[derive(Debug, Clone)]
544struct PendingCheck {
545    name: String,
546    expression: String,
547}
548
549#[derive(Debug, Clone)]
550struct PendingForeignKey {
551    name: String,
552    columns: Vec<String>,
553    referenced_table: String,
554    referenced_columns: Vec<String>,
555}
556
557/// Schema-first 表构建器。
558#[derive(Debug, Clone)]
559#[must_use = "表构建器必须调用 build"]
560pub struct Table {
561    name: String,
562    label: Option<String>,
563    datasource: Option<DatasourceId>,
564    primary_key_order: Vec<String>,
565    fields: Vec<Field>,
566    opaque_columns: Vec<OpaqueColumnConfig>,
567    indexes: Vec<PendingIndex>,
568    checks: Vec<PendingCheck>,
569    foreign_keys: Vec<PendingForeignKey>,
570    default_order: Vec<Order>,
571}
572
573impl Table {
574    /// 创建表定义构建器。
575    pub fn new(name: impl Into<String>) -> Self {
576        Self {
577            name: name.into(),
578            label: None,
579            datasource: None,
580            primary_key_order: Vec::new(),
581            fields: Vec::new(),
582            opaque_columns: Vec::new(),
583            indexes: Vec::new(),
584            checks: Vec::new(),
585            foreign_keys: Vec::new(),
586            default_order: Vec::new(),
587        }
588    }
589
590    /// 设置表展示名称。
591    pub fn label(mut self, label: impl Into<String>) -> Self {
592        self.label = Some(label.into());
593        self
594    }
595
596    /// 设置表所属逻辑数据源(默认 `default`)。
597    pub fn datasource(mut self, id: DatasourceId) -> Self {
598        self.datasource = Some(id);
599        self
600    }
601
602    /// 覆盖复合主键的列顺序(用于抵消字段排序)。
603    pub fn primary_key_order(mut self, order: Vec<String>) -> Self {
604        self.primary_key_order = order;
605        self
606    }
607
608    /// 批量添加字段;支持数组、`Vec` 和任意字段迭代器。
609    pub fn fields<I>(mut self, fields: I) -> Self
610    where
611        I: IntoIterator<Item = Field>,
612    {
613        self.fields.extend(fields);
614        self
615    }
616
617    /// 声明一个框架不建模的存量列(仅 PostgreSQL)。
618    ///
619    /// 该列必须已存在且 `format_type` 与 `sql_type` 一致;框架不改写、不读取、
620    /// 不写入,也不投影到通用 CRUD/UI。用于 `inet`、`citext`、自定义 domain 等
621    /// 无法安全映射为通用字段类型的列。
622    pub fn opaque_column(mut self, name: impl Into<String>, sql_type: impl Into<String>) -> Self {
623        self.opaque_columns.push(OpaqueColumnConfig {
624            name: name.into(),
625            sql_type: sql_type.into(),
626        });
627        self
628    }
629
630    /// 添加复合唯一索引。
631    pub fn unique<I, C>(mut self, fields: I) -> Self
632    where
633        I: IntoIterator<Item = C>,
634        C: Into<ColumnName>,
635    {
636        self.indexes.push(PendingIndex {
637            name: None,
638            fields: fields
639                .into_iter()
640                .map(|field| field.into().into_name())
641                .collect(),
642            expressions: Vec::new(),
643            predicate: None,
644            unique: true,
645            nulls_not_distinct: false,
646        });
647        self
648    }
649
650    /// 添加指定名称的复合唯一索引。
651    pub fn unique_named<I, C>(mut self, name: impl Into<String>, fields: I) -> Self
652    where
653        I: IntoIterator<Item = C>,
654        C: Into<ColumnName>,
655    {
656        self.indexes.push(PendingIndex {
657            name: Some(name.into()),
658            fields: fields
659                .into_iter()
660                .map(|field| field.into().into_name())
661                .collect(),
662            expressions: Vec::new(),
663            predicate: None,
664            unique: true,
665            nulls_not_distinct: false,
666        });
667        self
668    }
669
670    /// 添加复合唯一索引,并声明 PostgreSQL 15+ 的 `NULLS NOT DISTINCT` 语义。
671    ///
672    /// 空值互不异:两行该索引列均为 NULL 时会触发唯一冲突。仅 PostgreSQL 支持;
673    /// MySQL 在 schema 同步时明确拒绝该标志。
674    pub fn unique_nulls_not_distinct<I, C>(mut self, fields: I) -> Self
675    where
676        I: IntoIterator<Item = C>,
677        C: Into<ColumnName>,
678    {
679        self.indexes.push(PendingIndex {
680            name: None,
681            fields: fields
682                .into_iter()
683                .map(|field| field.into().into_name())
684                .collect(),
685            expressions: Vec::new(),
686            predicate: None,
687            unique: true,
688            nulls_not_distinct: true,
689        });
690        self
691    }
692
693    /// 添加指定名称的复合唯一索引,并声明 `NULLS NOT DISTINCT` 语义。
694    pub fn unique_named_nulls_not_distinct<I, C>(
695        mut self,
696        name: impl Into<String>,
697        fields: I,
698    ) -> Self
699    where
700        I: IntoIterator<Item = C>,
701        C: Into<ColumnName>,
702    {
703        self.indexes.push(PendingIndex {
704            name: Some(name.into()),
705            fields: fields
706                .into_iter()
707                .map(|field| field.into().into_name())
708                .collect(),
709            expressions: Vec::new(),
710            predicate: None,
711            unique: true,
712            nulls_not_distinct: true,
713        });
714        self
715    }
716
717    /// 添加复合普通索引。
718    pub fn index<I, C>(mut self, fields: I) -> Self
719    where
720        I: IntoIterator<Item = C>,
721        C: Into<ColumnName>,
722    {
723        self.indexes.push(PendingIndex {
724            name: None,
725            fields: fields
726                .into_iter()
727                .map(|field| field.into().into_name())
728                .collect(),
729            expressions: Vec::new(),
730            predicate: None,
731            unique: false,
732            nulls_not_distinct: false,
733        });
734        self
735    }
736
737    /// 添加指定名称的复合普通索引。
738    pub fn index_named<I, C>(mut self, name: impl Into<String>, fields: I) -> Self
739    where
740        I: IntoIterator<Item = C>,
741        C: Into<ColumnName>,
742    {
743        self.indexes.push(PendingIndex {
744            name: Some(name.into()),
745            fields: fields
746                .into_iter()
747                .map(|field| field.into().into_name())
748                .collect(),
749            expressions: Vec::new(),
750            predicate: None,
751            unique: false,
752            nulls_not_distinct: false,
753        });
754        self
755    }
756
757    /// 添加带受信表达式键与/或部分索引谓词的索引(仅 PostgreSQL 支持)。
758    ///
759    /// `fields` 与 `expressions` 至少一个非空;`predicate` 是 `WHERE` 后原样
760    /// 渲染的受信 SQL 表达式。MySQL 在 schema 同步时明确拒绝部分/表达式索引。
761    pub fn index_spec<I, C, S>(
762        mut self,
763        name: Option<String>,
764        fields: I,
765        expressions: impl IntoIterator<Item = S>,
766        predicate: Option<String>,
767        unique: bool,
768        nulls_not_distinct: bool,
769    ) -> Self
770    where
771        I: IntoIterator<Item = C>,
772        C: Into<ColumnName>,
773        S: Into<String>,
774    {
775        self.indexes.push(PendingIndex {
776            name,
777            fields: fields
778                .into_iter()
779                .map(|field| field.into().into_name())
780                .collect(),
781            expressions: expressions.into_iter().map(Into::into).collect(),
782            predicate,
783            unique,
784            nulls_not_distinct,
785        });
786        self
787    }
788
789    /// 添加指定名称的 MySQL CHECK 约束。
790    ///
791    /// 表达式属于受信任的应用定义,不得来自请求或运行时配置。
792    pub fn check_named(mut self, name: impl Into<String>, expression: impl Into<String>) -> Self {
793        self.checks.push(PendingCheck {
794            name: name.into(),
795            expression: expression.into(),
796        });
797        self
798    }
799
800    /// 添加指定名称的复合外键;更新和删除规则固定为 `RESTRICT`。
801    pub fn foreign_key_named<I, C, R, RC>(
802        mut self,
803        name: impl Into<String>,
804        columns: I,
805        referenced_table: impl Into<String>,
806        referenced_columns: R,
807    ) -> Self
808    where
809        I: IntoIterator<Item = C>,
810        C: Into<ColumnName>,
811        R: IntoIterator<Item = RC>,
812        RC: Into<ColumnName>,
813    {
814        self.foreign_keys.push(PendingForeignKey {
815            name: name.into(),
816            columns: columns
817                .into_iter()
818                .map(|column| column.into().into_name())
819                .collect(),
820            referenced_table: referenced_table.into(),
821            referenced_columns: referenced_columns
822                .into_iter()
823                .map(|column| column.into().into_name())
824                .collect(),
825        });
826        self
827    }
828
829    /// 设置首个默认排序规则。
830    pub fn default_order(mut self, order: Order) -> Self {
831        self.default_order = vec![order];
832        self
833    }
834
835    /// 追加默认排序规则。
836    pub fn then_order(mut self, order: Order) -> Self {
837        self.default_order.push(order);
838        self
839    }
840
841    /// 校验并生成不可变表定义。
842    pub fn build(self) -> Result<TableDefinition, BaseError> {
843        validate_identifier("表", &self.name)?;
844        if self.fields.is_empty() {
845            return Err(BaseError::ConfigError(format!(
846                "表 {} 至少需要一个字段",
847                self.name
848            )));
849        }
850
851        let mut field_names = HashSet::with_capacity(self.fields.len());
852        let mut legacy_names = HashSet::new();
853        let mut configs = HashMap::with_capacity(self.fields.len());
854        let mut primary_keys: Vec<String> = Vec::new();
855        let mut created_at: Option<String> = None;
856        let mut updated_at: Option<String> = None;
857        let mut deleted_at: Option<String> = None;
858        let mut soft_delete: Option<String> = None;
859        let mut tenant_key: Option<String> = None;
860        let mut indexes = self.indexes;
861        let checks = self.checks;
862        let foreign_keys = self.foreign_keys;
863        // 启动期默认值校验复用同一个有界正则缓存(每表构建一次,构建完即丢弃)。
864        let regex_cache = RegexCache::default();
865
866        for mut field in self.fields {
867            validate_identifier("字段", &field.config.name)?;
868            if !field_names.insert(field.config.name.clone()) {
869                return Err(BaseError::ConfigError(format!(
870                    "表 {} 存在重复字段: {}",
871                    self.name, field.config.name
872                )));
873            }
874            if let Some(legacy_name) = field.config.renamed_from.as_deref() {
875                validate_identifier("旧字段", legacy_name)?;
876                if legacy_name == field.config.name || !legacy_names.insert(legacy_name.to_string())
877                {
878                    return Err(BaseError::ConfigError(format!(
879                        "表 {} 的旧字段改名来源重复或未发生改名: {}",
880                        self.name, legacy_name
881                    )));
882                }
883            }
884            if field.config.display_name.is_empty() {
885                field.config.display_name = field.config.name.clone();
886            }
887            if let Some(display_fields) = field.relation_display_fields.take() {
888                let relation = field.config.relation.as_mut().ok_or_else(|| {
889                    BaseError::ConfigError(format!(
890                        "表 {} 的字段 {} 未定义 relation,不能配置关联展示字段",
891                        self.name, field.config.name
892                    ))
893                })?;
894                relation.display_fields = display_fields;
895            }
896            validate_field_shape(&self.name, &field, &regex_cache)?;
897
898            if field.primary_key {
899                primary_keys.push(field.config.name.clone());
900            }
901            if field.config.tenant_key && tenant_key.replace(field.config.name.clone()).is_some() {
902                return Err(BaseError::ConfigError(format!(
903                    "表 {} 只能定义一个租户隔离字段",
904                    self.name
905                )));
906            }
907            set_unique_role(
908                &self.name,
909                "created_at",
910                field.created_at,
911                &field.config.name,
912                &mut created_at,
913            )?;
914            set_unique_role(
915                &self.name,
916                "updated_at",
917                field.updated_at,
918                &field.config.name,
919                &mut updated_at,
920            )?;
921            set_unique_role(
922                &self.name,
923                "deleted_at",
924                field.deleted_at,
925                &field.config.name,
926                &mut deleted_at,
927            )?;
928            set_unique_role(
929                &self.name,
930                "soft_delete",
931                field.soft_delete,
932                &field.config.name,
933                &mut soft_delete,
934            )?;
935
936            if field.unique {
937                indexes.push(PendingIndex {
938                    name: field.unique_name.take(),
939                    fields: vec![field.config.name.clone()],
940                    expressions: Vec::new(),
941                    predicate: None,
942                    unique: true,
943                    nulls_not_distinct: false,
944                });
945            }
946            if field.index {
947                indexes.push(PendingIndex {
948                    name: field.index_name.take(),
949                    fields: vec![field.config.name.clone()],
950                    expressions: Vec::new(),
951                    predicate: None,
952                    unique: false,
953                    nulls_not_distinct: false,
954                });
955            }
956            configs.insert(field.config.name.clone(), field.config);
957        }
958
959        let mut opaque_names = HashSet::new();
960        for opaque in &self.opaque_columns {
961            validate_identifier("Opaque 列", &opaque.name)?;
962            if field_names.contains(&opaque.name) || !opaque_names.insert(opaque.name.clone()) {
963                return Err(BaseError::ConfigError(format!(
964                    "表 {} 的 opaque 列 {} 与字段或另一 opaque 列重名",
965                    self.name, opaque.name
966                )));
967            }
968            let sql_type = opaque.sql_type.trim();
969            if sql_type.is_empty()
970                || sql_type.chars().count() > 256
971                || [";", "--", "/*", "*/", "\n", "\r", "\0"]
972                    .iter()
973                    .any(|marker| sql_type.contains(marker))
974            {
975                return Err(BaseError::ConfigError(format!(
976                    "表 {} 的 opaque 列 {} 必须声明非空、长度受限且不含语句分隔符的类型文本",
977                    self.name, opaque.name
978                )));
979            }
980        }
981
982        if let Some(legacy_name) = legacy_names
983            .iter()
984            .find(|legacy_name| field_names.contains(legacy_name.as_str()))
985        {
986            return Err(BaseError::ConfigError(format!(
987                "表 {} 同时声明旧字段与改名后字段: {}",
988                self.name, legacy_name
989            )));
990        }
991
992        if !self.primary_key_order.is_empty() {
993            let mut ordered = Vec::with_capacity(primary_keys.len());
994            for name in &self.primary_key_order {
995                match primary_keys.iter().position(|key| key == name) {
996                    Some(position) => ordered.push(primary_keys.remove(position)),
997                    None => {
998                        return Err(BaseError::ConfigError(format!(
999                            "表 {} 的主键顺序引用非主键字段: {name}",
1000                            self.name
1001                        )))
1002                    }
1003                }
1004            }
1005            ordered.append(&mut primary_keys);
1006            primary_keys = ordered;
1007        }
1008
1009        let primary_key = primary_keys.first().cloned().unwrap_or_default();
1010
1011        let mut unique_indexes = Vec::new();
1012        let mut normal_indexes = Vec::new();
1013        let mut index_names = HashSet::new();
1014        for index in indexes {
1015            validate_index(&self.name, &field_names, &index, &mut index_names)?;
1016            let config = IndexConfig::new(index.name, index.fields, index.nulls_not_distinct)
1017                .with_expressions(index.expressions)
1018                .with_predicate(index.predicate);
1019            if index.unique {
1020                unique_indexes.push(config);
1021            } else {
1022                normal_indexes.push(config);
1023            }
1024        }
1025
1026        let mut constraint_names = HashSet::new();
1027        let checks = checks
1028            .into_iter()
1029            .map(|check| {
1030                validate_constraint_name(&self.name, &check.name, &mut constraint_names)?;
1031                validate_check_expression(&self.name, &check.name, &check.expression)?;
1032                Ok(CheckConfig {
1033                    name: check.name,
1034                    expression: check.expression,
1035                })
1036            })
1037            .collect::<Result<Vec<_>, BaseError>>()?;
1038        let foreign_keys = foreign_keys
1039            .into_iter()
1040            .map(|foreign_key| {
1041                validate_constraint_name(&self.name, &foreign_key.name, &mut constraint_names)?;
1042                validate_foreign_key(&self.name, &field_names, &foreign_key)?;
1043                Ok(ForeignKeyConfig {
1044                    name: foreign_key.name,
1045                    columns: foreign_key.columns,
1046                    referenced_table: foreign_key.referenced_table,
1047                    referenced_columns: foreign_key.referenced_columns,
1048                })
1049            })
1050            .collect::<Result<Vec<_>, BaseError>>()?;
1051
1052        let mut orders = Vec::with_capacity(self.default_order.len());
1053        for order in self.default_order {
1054            if !field_names.contains(&order.field) {
1055                return Err(BaseError::ConfigError(format!(
1056                    "表 {} 的默认排序字段不存在: {}",
1057                    self.name, order.field
1058                )));
1059            }
1060            orders.push((order.field, order.direction));
1061        }
1062
1063        let timestamp_fields =
1064            if created_at.is_some() || updated_at.is_some() || deleted_at.is_some() {
1065                Some(TimestampFields::new(created_at, updated_at, deleted_at))
1066            } else {
1067                None
1068            };
1069        let table_ref = yang_db::TableRef::new(self.name.clone())
1070            .map_err(|error| BaseError::ConfigError(error.to_string()))?;
1071        let field_refs = field_names
1072            .iter()
1073            .map(|name| {
1074                yang_db::FieldRef::new(name.clone())
1075                    .map(|field| (name.clone(), field))
1076                    .map_err(|error| BaseError::ConfigError(error.to_string()))
1077            })
1078            .collect::<Result<HashMap<_, _>, _>>()?;
1079
1080        Ok(TableDefinition {
1081            config: Arc::new(TableConfig {
1082                table_name: self.name.clone(),
1083                datasource: self.datasource.unwrap_or_default(),
1084                table_ref,
1085                display_name: self.label.unwrap_or(self.name),
1086                primary_key,
1087                primary_keys,
1088                fields: configs,
1089                opaque_columns: self.opaque_columns,
1090                field_refs,
1091                unique_indexes,
1092                indexes: normal_indexes,
1093                checks,
1094                foreign_keys,
1095                default_order: orders,
1096                soft_delete_field: soft_delete,
1097                timestamp_fields,
1098            }),
1099        })
1100    }
1101}
1102
1103/// 不可变的数据表定义。
1104#[derive(Debug, Clone)]
1105pub struct TableDefinition {
1106    pub(crate) config: Arc<TableConfig>,
1107}
1108
1109impl TableDefinition {
1110    /// 返回数据库表名。
1111    pub fn name(&self) -> &str {
1112        &self.config.table_name
1113    }
1114
1115    /// 返回表所属逻辑数据源。
1116    pub fn datasource(&self) -> &DatasourceId {
1117        &self.config.datasource
1118    }
1119
1120    /// 返回展示名称。
1121    pub fn label(&self) -> &str {
1122        &self.config.display_name
1123    }
1124
1125    /// 返回主键字段名。
1126    pub fn primary_key(&self) -> &str {
1127        &self.config.primary_key
1128    }
1129
1130    /// 返回完整主键列(复合主键时大于一个元素)。
1131    pub fn primary_keys(&self) -> &[String] {
1132        &self.config.primary_keys
1133    }
1134
1135    /// 返回字段数量。
1136    pub fn field_count(&self) -> usize {
1137        self.config.fields.len()
1138    }
1139
1140    /// 按数据库字段名读取元数据。
1141    pub fn field(&self, name: &str) -> Option<FieldMetadata<'_>> {
1142        self.config
1143            .fields
1144            .get(name)
1145            .map(|config| FieldMetadata { config })
1146    }
1147
1148    /// 按字段名排序返回全部字段元数据。
1149    pub fn fields(&self) -> Vec<FieldMetadata<'_>> {
1150        let mut fields: Vec<_> = self
1151            .config
1152            .fields
1153            .values()
1154            .map(|config| FieldMetadata { config })
1155            .collect();
1156        fields.sort_by(|left, right| left.name().cmp(right.name()));
1157        fields
1158    }
1159
1160    /// 返回软删除字段名。
1161    pub fn soft_delete_field(&self) -> Option<&str> {
1162        self.config.soft_delete_field.as_deref()
1163    }
1164
1165    /// 返回唯一租户隔离字段;表未声明租户字段时返回 `None`。
1166    pub fn tenant_key_field(&self) -> Option<&str> {
1167        self.config
1168            .fields
1169            .values()
1170            .find(|field| field.tenant_key)
1171            .map(|field| field.name.as_str())
1172    }
1173
1174    /// 生成供 API catalog 使用的全局写入侧 JSON Schema。
1175    ///
1176    /// 该 schema 是所有角色可写字段的并集;面向当前请求返回结构时应使用
1177    /// `Self::input_schema_for_roles`。
1178    pub fn input_schema(&self) -> Value {
1179        self.json_schema(false, None)
1180    }
1181
1182    /// 生成供 API catalog 使用的全局读取侧 JSON Schema。
1183    ///
1184    /// 该 schema 是所有角色可读字段的并集;面向当前请求返回结构时应使用
1185    /// `Self::output_schema_for_roles`。
1186    pub fn output_schema(&self) -> Value {
1187        self.json_schema(true, None)
1188    }
1189
1190    /// 按当前用户角色生成写入侧 JSON Schema。
1191    pub fn input_schema_for_roles(&self, roles: &HashSet<String>) -> Value {
1192        self.json_schema(false, Some(roles))
1193    }
1194
1195    /// 按当前用户角色生成读取侧 JSON Schema。
1196    pub fn output_schema_for_roles(&self, roles: &HashSet<String>) -> Value {
1197        self.json_schema(true, Some(roles))
1198    }
1199
1200    /// 返回指定数据库字段的底层 JSON Schema,供内置 API 描述投影使用。
1201    #[cfg(any(feature = "mysql", feature = "postgres"))]
1202    pub(crate) fn field_schema(&self, name: &str) -> Option<Value> {
1203        self.config.fields.get(name).map(field_json_schema)
1204    }
1205
1206    fn json_schema(&self, output: bool, roles: Option<&HashSet<String>>) -> Value {
1207        let mut properties = Map::new();
1208        let mut required = Vec::new();
1209        let mut names: Vec<_> = self.config.fields.keys().collect();
1210        names.sort();
1211        for name in names {
1212            let field = &self.config.fields[name];
1213            let generated = field.auto_increment
1214                || self
1215                    .config
1216                    .timestamp_fields
1217                    .as_ref()
1218                    .is_some_and(|timestamps| {
1219                        timestamps.created_at.as_deref() == Some(name.as_str())
1220                            || timestamps.updated_at.as_deref() == Some(name.as_str())
1221                            || timestamps.deleted_at.as_deref() == Some(name.as_str())
1222                    })
1223                || self.config.soft_delete_field.as_deref() == Some(name.as_str());
1224            let audience = if output {
1225                &field.permissions.readable
1226            } else {
1227                &field.permissions.writable
1228            };
1229            let audience_allows = roles.map_or_else(
1230                || !matches!(audience, Audience::Nobody),
1231                |roles| audience.allows(roles),
1232            );
1233            if field.hidden || !audience_allows || (!output && generated) {
1234                continue;
1235            }
1236            properties.insert(name.clone(), field_json_schema(field));
1237            if field.required && (output || (!generated && field.default_value.is_none())) {
1238                required.push(Value::String(name.clone()));
1239            }
1240        }
1241        json!({
1242            "type": "object",
1243            "title": self.config.display_name,
1244            "properties": properties,
1245            "required": required,
1246            "additionalProperties": false,
1247        })
1248    }
1249
1250    #[cfg(feature = "mysql")]
1251    pub(crate) fn config(&self) -> &TableConfig {
1252        &self.config
1253    }
1254
1255    pub(crate) fn shared_config(&self) -> Arc<TableConfig> {
1256        Arc::clone(&self.config)
1257    }
1258
1259    /// 校验实际数据库列是否兼容当前表定义。
1260    pub fn validate_schema(
1261        &self,
1262        columns: &[super::SchemaColumn],
1263    ) -> super::SchemaValidationReport {
1264        self.config.validate_schema(columns)
1265    }
1266
1267    /// 将表定义绑定到 MySQL 连接池(兼容入口)。
1268    ///
1269    /// 内部会包装为 [`AnyPool::MySql`](crate::database::AnyPool);需要 PostgreSQL
1270    /// 或其他运行时后端时请使用 [`TableDefinition::bind_pool`]。
1271    #[cfg(feature = "mysql")]
1272    pub fn bind(&self, pool: Arc<sqlx::MySqlPool>) -> TableHandle {
1273        self.bind_pool(crate::database::AnyPool::MySql(pool))
1274    }
1275
1276    /// 将表定义绑定到任意受支持的数据库连接池(沿用表声明的数据源)。
1277    #[cfg(any(feature = "mysql", feature = "postgres"))]
1278    pub fn bind_pool(&self, pool: crate::database::AnyPool) -> TableHandle {
1279        self.bind_source_pool(crate::database::PoolHandle::new(
1280            self.datasource().clone(),
1281            pool,
1282        ))
1283    }
1284
1285    /// 将表定义绑定到注册表中的具名数据源(推荐入口)。
1286    #[cfg(any(feature = "mysql", feature = "postgres"))]
1287    pub fn bind_datasource(&self, datasource: &crate::database::Datasource) -> TableHandle {
1288        self.bind_source_pool(crate::database::PoolHandle::new(
1289            datasource.id().clone(),
1290            datasource.database().pool(),
1291        ))
1292    }
1293
1294    /// 将表定义绑定到带逻辑数据源身份的连接池句柄。
1295    #[cfg(any(feature = "mysql", feature = "postgres"))]
1296    pub fn bind_source_pool(&self, pool: crate::database::PoolHandle) -> TableHandle {
1297        TableHandle {
1298            definition: self.clone(),
1299            pool,
1300        }
1301    }
1302}
1303
1304/// 只读字段元数据视图。
1305#[derive(Debug, Clone, Copy)]
1306pub struct FieldMetadata<'a> {
1307    config: &'a FieldConfig,
1308}
1309
1310impl<'a> FieldMetadata<'a> {
1311    /// 返回数据库字段名。
1312    pub fn name(self) -> &'a str {
1313        &self.config.name
1314    }
1315
1316    /// 返回展示名称。
1317    pub fn label(self) -> &'a str {
1318        &self.config.display_name
1319    }
1320
1321    /// 返回字段是否承担租户隔离键语义。
1322    pub fn is_tenant_key(self) -> bool {
1323        self.config.tenant_key
1324    }
1325
1326    /// 返回字段类型。
1327    pub fn field_type(self) -> &'a FieldType {
1328        &self.config.field_type
1329    }
1330
1331    /// 返回字段是否必填。
1332    pub fn is_required(self) -> bool {
1333        self.config.required
1334    }
1335
1336    /// 返回字段默认值。
1337    pub fn default_value(self) -> Option<&'a Value> {
1338        self.config.default_value.as_ref()
1339    }
1340
1341    /// 返回字段是否由数据库自增生成。
1342    pub fn is_auto_increment(self) -> bool {
1343        self.config.auto_increment
1344    }
1345
1346    /// 返回字段是否允许关键词搜索。
1347    pub fn is_searchable(self) -> bool {
1348        self.config.searchable
1349    }
1350
1351    /// 返回字段是否允许筛选。
1352    pub fn is_filterable(self) -> bool {
1353        self.config.filterable
1354    }
1355
1356    /// 返回字段是否允许排序。
1357    pub fn is_sortable(self) -> bool {
1358        self.config.sortable
1359    }
1360
1361    /// 返回字段是否从通用记录投影和表 JSON Schema 中隐藏。
1362    pub fn is_secret(self) -> bool {
1363        self.config.hidden
1364    }
1365}
1366
1367/// 绑定数据库连接池后的表句柄。
1368#[cfg(any(feature = "mysql", feature = "postgres"))]
1369#[derive(Debug, Clone)]
1370pub struct TableHandle {
1371    definition: TableDefinition,
1372    pool: crate::database::PoolHandle,
1373}
1374
1375#[cfg(any(feature = "mysql", feature = "postgres"))]
1376impl TableHandle {
1377    /// 返回不可变表定义。
1378    pub fn definition(&self) -> &TableDefinition {
1379        &self.definition
1380    }
1381
1382    /// 创建带字段权限保护的查询构建器。
1383    pub fn query<I, S>(&self, roles: I) -> TableQuery
1384    where
1385        I: IntoIterator<Item = S>,
1386        S: Into<String>,
1387    {
1388        let roles: Arc<[String]> =
1389            Arc::from(roles.into_iter().map(Into::into).collect::<Vec<String>>());
1390        TableQuery::new_sourced(
1391            self.definition.shared_config(),
1392            roles,
1393            Some(self.pool.pool().clone()),
1394            self.pool.source().clone(),
1395        )
1396    }
1397}
1398
1399fn validate_identifier(kind: &str, value: &str) -> Result<(), BaseError> {
1400    let mut chars = value.chars();
1401    let first = chars
1402        .next()
1403        .ok_or_else(|| BaseError::ConfigError(format!("{kind}名称不能为空")))?;
1404    if value.len() > 64
1405        || !(first == '_' || first.is_ascii_alphabetic())
1406        || !chars.all(|character| character == '_' || character.is_ascii_alphanumeric())
1407    {
1408        return Err(BaseError::ConfigError(format!("非法{kind}名称: {value}")));
1409    }
1410    Ok(())
1411}
1412
1413/// 生成列表达式的括号平衡校验。
1414///
1415/// 跳过单引号字符串(含 `''` 双写与 `E'...'` 反斜杠转义)与双引号标识符;
1416/// 顶层右括号使深度变负即拒绝,结束时深度必须为 0。用于阻止
1417/// `price) STORED, ...` 这类闭合外层 `GENERATED ALWAYS AS (` 的注入。
1418fn has_balanced_generated_expression(expression: &str) -> bool {
1419    let bytes = expression.as_bytes();
1420    let mut depth: i32 = 0;
1421    let mut index = 0;
1422    while index < bytes.len() {
1423        match bytes[index] {
1424            b'\'' => {
1425                let escape_string = is_escape_string_prefix(bytes, index);
1426                index += 1;
1427                while index < bytes.len() {
1428                    if escape_string && bytes[index] == b'\\' {
1429                        // E 字符串的反斜杠转义:跳过被转义的下一个字节。
1430                        index = (index + 2).min(bytes.len());
1431                        continue;
1432                    }
1433                    if bytes[index] == b'\'' {
1434                        if bytes.get(index + 1) == Some(&b'\'') {
1435                            index += 2;
1436                            continue;
1437                        }
1438                        index += 1;
1439                        break;
1440                    }
1441                    index += 1;
1442                }
1443            }
1444            b'"' => {
1445                index += 1;
1446                while index < bytes.len() {
1447                    if bytes[index] == b'"' {
1448                        if bytes.get(index + 1) == Some(&b'"') {
1449                            index += 2;
1450                            continue;
1451                        }
1452                        index += 1;
1453                        break;
1454                    }
1455                    index += 1;
1456                }
1457            }
1458            b'(' => {
1459                depth += 1;
1460                index += 1;
1461            }
1462            b')' => {
1463                depth -= 1;
1464                if depth < 0 {
1465                    return false;
1466                }
1467                index += 1;
1468            }
1469            _ => index += 1,
1470        }
1471    }
1472    depth == 0
1473}
1474
1475/// 判断 `'`(位于 `quote_index`)是否属于 PostgreSQL `E'...'` 转义字符串。
1476fn is_escape_string_prefix(bytes: &[u8], quote_index: usize) -> bool {
1477    if quote_index == 0 || !matches!(bytes[quote_index - 1], b'E' | b'e') {
1478        return false;
1479    }
1480    quote_index == 1 || !is_identifier_byte(bytes[quote_index - 2])
1481}
1482
1483fn is_identifier_byte(byte: u8) -> bool {
1484    byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$' || byte >= 0x80
1485}
1486
1487/// CHECK 表达式的跨方言括号平衡校验。
1488///
1489/// CHECK 与生成列一样原样拼接进 `CONSTRAINT ... CHECK ({expr})`。表达式必须
1490/// 能作为单条括号平衡的布尔表达式嵌入外层括号;仅当 PostgreSQL 与 MySQL
1491/// 两种词法都判定越界(顶层右括号使深度变负,或结束时深度非 0 / 引号未闭合)
1492/// 时才拒绝,避免误伤任一方言独有的合法字面量。
1493fn has_balanced_check_expression(expression: &str) -> bool {
1494    // 两种词法各自完整扫描后取并集:MySQL 合法而 PostgreSQL 不认识的词法
1495    //(反引号、`#` 注释、反斜杠转义字符串)由 MySQL 扫描保住,反之
1496    //(E 字符串、U& 转义、美元引号)由 PostgreSQL 扫描保住。
1497    has_balanced_pg_check_expression(expression) || has_balanced_mysql_check_expression(expression)
1498}
1499
1500/// PostgreSQL 词法下的括号平衡扫描。
1501///
1502/// 识别 `''` 双写、`E'...'` / `U&'...'` 反斜杠转义、`U&"..."` 与 `""` 双写、
1503/// 双引号标识符以及 `$tag$...$tag$` 美元引号;未闭合的引号视为越界。
1504pub(crate) fn has_balanced_pg_check_expression(expression: &str) -> bool {
1505    let bytes = expression.as_bytes();
1506    let mut depth: i32 = 0;
1507    let mut index = 0;
1508    while index < bytes.len() {
1509        match bytes[index] {
1510            b'\'' => {
1511                let backslash_escapes =
1512                    is_escape_string_prefix(bytes, index) || is_unicode_escape_prefix(bytes, index);
1513                if !skip_quoted(bytes, &mut index, b'\'', backslash_escapes) {
1514                    return false;
1515                }
1516            }
1517            b'"' => {
1518                let backslash_escapes = is_unicode_escape_prefix(bytes, index);
1519                if !skip_quoted(bytes, &mut index, b'"', backslash_escapes) {
1520                    return false;
1521                }
1522            }
1523            b'$' => {
1524                let Some(tag_end) = dollar_quote_tag_end(bytes, index) else {
1525                    index += 1;
1526                    continue;
1527                };
1528                let tag = &bytes[index..tag_end];
1529                let mut cursor = tag_end;
1530                loop {
1531                    if cursor + tag.len() > bytes.len() {
1532                        // 未闭合的美元引号无法嵌入单条表达式。
1533                        return false;
1534                    }
1535                    if &bytes[cursor..cursor + tag.len()] == tag {
1536                        index = cursor + tag.len();
1537                        break;
1538                    }
1539                    cursor += 1;
1540                }
1541            }
1542            b'(' => {
1543                depth += 1;
1544                index += 1;
1545            }
1546            b')' => {
1547                depth -= 1;
1548                if depth < 0 {
1549                    return false;
1550                }
1551                index += 1;
1552            }
1553            _ => index += 1,
1554        }
1555    }
1556    depth == 0
1557}
1558
1559/// MySQL 词法下的括号平衡扫描。
1560///
1561/// 识别单/双引号字符串的反斜杠转义与引号双写、反引号标识符双写以及 `#`
1562/// 行注释;`--` 与 `/* */` 已由上层黑名单统一拒绝。未闭合的引号视为越界。
1563pub(crate) fn has_balanced_mysql_check_expression(expression: &str) -> bool {
1564    let bytes = expression.as_bytes();
1565    let mut depth: i32 = 0;
1566    let mut index = 0;
1567    while index < bytes.len() {
1568        match bytes[index] {
1569            b'\'' => {
1570                if !skip_quoted(bytes, &mut index, b'\'', true) {
1571                    return false;
1572                }
1573            }
1574            b'"' => {
1575                if !skip_quoted(bytes, &mut index, b'"', true) {
1576                    return false;
1577                }
1578            }
1579            b'`' => {
1580                if !skip_quoted(bytes, &mut index, b'`', false) {
1581                    return false;
1582                }
1583            }
1584            b'#' => {
1585                while index < bytes.len() && bytes[index] != b'\n' {
1586                    index += 1;
1587                }
1588            }
1589            b'(' => {
1590                depth += 1;
1591                index += 1;
1592            }
1593            b')' => {
1594                depth -= 1;
1595                if depth < 0 {
1596                    return false;
1597                }
1598                index += 1;
1599            }
1600            _ => index += 1,
1601        }
1602    }
1603    depth == 0
1604}
1605
1606/// 跳过一段由 `delimiter` 包围的字符串或标识符,成功时把 `index` 移到闭合
1607/// 引号之后;`backslash_escapes` 为真时识别反斜杠转义。两种方言都支持把
1608/// 引号写成双写来转义。未闭合返回 false。
1609fn skip_quoted(bytes: &[u8], index: &mut usize, delimiter: u8, backslash_escapes: bool) -> bool {
1610    *index += 1;
1611    while *index < bytes.len() {
1612        if backslash_escapes && bytes[*index] == b'\\' {
1613            *index = (*index + 2).min(bytes.len());
1614            continue;
1615        }
1616        if bytes[*index] == delimiter {
1617            if bytes.get(*index + 1) == Some(&delimiter) {
1618                *index += 2;
1619                continue;
1620            }
1621            *index += 1;
1622            return true;
1623        }
1624        *index += 1;
1625    }
1626    false
1627}
1628
1629/// 判断引号(位于 `quote_index`)是否属于 PostgreSQL `U&'...'` / `U&"..."` 前缀。
1630fn is_unicode_escape_prefix(bytes: &[u8], quote_index: usize) -> bool {
1631    if quote_index < 2
1632        || bytes[quote_index - 1] != b'&'
1633        || !matches!(bytes[quote_index - 2], b'U' | b'u')
1634    {
1635        return false;
1636    }
1637    quote_index < 3 || !is_identifier_byte(bytes[quote_index - 3])
1638}
1639
1640/// 识别 PostgreSQL 美元引号起始 `$tag$`,返回 tag(含首尾 `$`)的结束下标。
1641fn dollar_quote_tag_end(bytes: &[u8], start: usize) -> Option<usize> {
1642    let mut index = start + 1;
1643    let first = bytes.get(index)?;
1644    if *first == b'$' {
1645        // `$$...$$`:空 tag。
1646        return Some(index + 1);
1647    }
1648    if !(*first == b'_' || first.is_ascii_alphabetic() || *first >= 0x80) {
1649        return None;
1650    }
1651    index += 1;
1652    while let Some(byte) = bytes.get(index) {
1653        if byte.is_ascii_alphanumeric() || *byte == b'_' || *byte >= 0x80 {
1654            index += 1;
1655        } else {
1656            break;
1657        }
1658    }
1659    (bytes.get(index) == Some(&b'$')).then_some(index + 1)
1660}
1661
1662fn validate_field_shape(table: &str, field: &Field, cache: &RegexCache) -> Result<(), BaseError> {
1663    match &field.config.field_type {
1664        FieldType::String { max_length } if !(1..=MAX_VARCHAR_LENGTH).contains(max_length) => {
1665            return Err(BaseError::ConfigError(format!(
1666                "表 {table} 的字符串字段 {} 长度必须在 1..={MAX_VARCHAR_LENGTH}(更长内容请使用 Text 字段)",
1667                field.config.name
1668            )));
1669        }
1670        FieldType::Enum { values } => {
1671            let unique: HashSet<_> = values.iter().collect();
1672            if values.is_empty() || unique.len() != values.len() {
1673                return Err(BaseError::ConfigError(format!(
1674                    "表 {table} 的枚举字段 {} 必须提供非空且不重复的候选值",
1675                    field.config.name
1676                )));
1677            }
1678        }
1679        FieldType::Decimal { precision, scale }
1680            if *precision == 0 || *precision > 65 || *scale > *precision =>
1681        {
1682            return Err(BaseError::ConfigError(format!(
1683                "表 {table} 的 DECIMAL 字段 {} 必须满足 1 <= precision <= 65 且 scale <= precision",
1684                field.config.name
1685            )));
1686        }
1687        FieldType::Array(element) if matches!(**element, FieldType::Array(_) | FieldType::Json) => {
1688            return Err(BaseError::ConfigError(format!(
1689                "表 {table} 的数组字段 {} 只支持标量元素,不支持嵌套数组或 JSON 元素",
1690                field.config.name
1691            )));
1692        }
1693        _ => {}
1694    }
1695
1696    if let Some(type_name) = &field.config.native_enum {
1697        if !matches!(field.config.field_type, FieldType::Enum { .. }) {
1698            return Err(BaseError::ConfigError(format!(
1699                "表 {table} 的字段 {} 只有枚举类型可以声明 native_enum",
1700                field.config.name
1701            )));
1702        }
1703        validate_identifier("枚举类型", type_name)?;
1704        // PostgreSQL 标识符上限是 63 字节;通用校验的 64 字符上界不能替代。
1705        if type_name.len() > 63 {
1706            return Err(BaseError::ConfigError(format!(
1707                "表 {table} 的枚举类型名 {type_name} 超过 PostgreSQL 63 字节限制"
1708            )));
1709        }
1710    }
1711
1712    if field.config.auto_increment
1713        && (!field.primary_key
1714            || !matches!(
1715                field.config.field_type,
1716                FieldType::Integer | FieldType::BigInt
1717            ))
1718    {
1719        return Err(BaseError::ConfigError(format!(
1720            "表 {table} 的 auto_increment 仅允许用于整数主键字段: {}",
1721            field.config.name
1722        )));
1723    }
1724    if field.primary_key && !field.config.required {
1725        return Err(BaseError::ConfigError(format!(
1726            "表 {table} 的主键必须为必填字段: {}",
1727            field.config.name
1728        )));
1729    }
1730    if field.config.auto_increment && field.config.default_value.is_some() {
1731        return Err(BaseError::ConfigError(format!(
1732            "表 {table} 的自增字段不能配置默认值: {}",
1733            field.config.name
1734        )));
1735    }
1736    if let Some(expression) = &field.config.generated {
1737        let expression = expression.trim();
1738        if expression.is_empty()
1739            || expression.chars().count() > 2_048
1740            || [";", "--", "/*", "*/"]
1741                .iter()
1742                .any(|marker| expression.contains(marker))
1743            || !has_balanced_generated_expression(expression)
1744        {
1745            return Err(BaseError::ConfigError(format!(
1746                "表 {table} 的生成列 {} 必须是单条、非空、长度受限且括号平衡的受信表达式",
1747                field.config.name
1748            )));
1749        }
1750        if field.config.auto_increment || field.config.default_value.is_some() {
1751            return Err(BaseError::ConfigError(format!(
1752                "表 {table} 的生成列 {} 不能同时声明自增或默认值",
1753                field.config.name
1754            )));
1755        }
1756    }
1757    if let Some(collation) = &field.config.collation {
1758        if collation.trim().is_empty() || collation.len() > 128 {
1759            return Err(BaseError::ConfigError(format!(
1760                "表 {table} 的字段 {} 声明了空或过长的 collation",
1761                field.config.name
1762            )));
1763        }
1764    }
1765    validate_validator_configuration(table, &field.config)?;
1766    if let Some(default) = &field.config.default_value {
1767        if matches!(
1768            field.config.field_type,
1769            FieldType::Text | FieldType::Json | FieldType::Bytes | FieldType::Array(_)
1770        ) {
1771            return Err(BaseError::ConfigError(format!(
1772                "表 {table} 的 TEXT/JSON/BYTES/ARRAY 字段不能配置数据库默认值: {}",
1773                field.config.name
1774            )));
1775        }
1776        field.config.validate(default, cache)?;
1777    }
1778    validate_audience(
1779        table,
1780        &field.config.name,
1781        "读取",
1782        &field.config.permissions.readable,
1783    )?;
1784    validate_audience(
1785        table,
1786        &field.config.name,
1787        "写入",
1788        &field.config.permissions.writable,
1789    )?;
1790    validate_audience(
1791        table,
1792        &field.config.name,
1793        "筛选",
1794        &field.config.permissions.filterable,
1795    )?;
1796    validate_audience(
1797        table,
1798        &field.config.name,
1799        "排序",
1800        &field.config.permissions.sortable,
1801    )?;
1802    if let Some(relation) = &field.config.relation {
1803        validate_identifier("关联表", &relation.table)?;
1804        validate_identifier("关联字段", &relation.field)?;
1805        for display_field in &relation.display_fields {
1806            validate_identifier("关联展示字段", display_field)?;
1807        }
1808    }
1809    if (field.created_at || field.updated_at || field.deleted_at || field.soft_delete)
1810        && !matches!(
1811            field.config.field_type,
1812            FieldType::Integer | FieldType::BigInt | FieldType::Timestamp
1813        )
1814    {
1815        return Err(BaseError::ConfigError(format!(
1816            "表 {table} 的时间戳语义字段必须是整数或 Timestamp: {}",
1817            field.config.name
1818        )));
1819    }
1820    Ok(())
1821}
1822
1823fn validate_validator_configuration(table: &str, field: &FieldConfig) -> Result<(), BaseError> {
1824    let string_compatible = matches!(
1825        field.field_type,
1826        FieldType::String { .. }
1827            | FieldType::Text
1828            | FieldType::Enum { .. }
1829            | FieldType::Date
1830            | FieldType::DateTime
1831    );
1832    let numeric_compatible = matches!(
1833        field.field_type,
1834        FieldType::Integer
1835            | FieldType::BigInt
1836            | FieldType::Float
1837            | FieldType::Double
1838            | FieldType::Decimal { .. }
1839            | FieldType::Timestamp
1840    );
1841    let mut min_length: Option<usize> = None;
1842    let mut max_length: Option<usize> = None;
1843    let mut minimum: Option<f64> = None;
1844    let mut maximum: Option<f64> = None;
1845
1846    for validator in &field.validators {
1847        match validator {
1848            Validator::MinLength(value) => {
1849                ensure_validator_type(table, field, validator, string_compatible)?;
1850                min_length = Some(min_length.map_or(*value, |current| current.max(*value)));
1851            }
1852            Validator::MaxLength(value) => {
1853                ensure_validator_type(table, field, validator, string_compatible)?;
1854                max_length = Some(max_length.map_or(*value, |current| current.min(*value)));
1855            }
1856            Validator::Min(value) => {
1857                ensure_validator_type(table, field, validator, numeric_compatible)?;
1858                if !value.is_finite() {
1859                    return Err(BaseError::ConfigError(format!(
1860                        "表 {table} 的字段 {} 数值下限必须是有限数值",
1861                        field.name
1862                    )));
1863                }
1864                minimum = Some(minimum.map_or(*value, |current| current.max(*value)));
1865            }
1866            Validator::Max(value) => {
1867                ensure_validator_type(table, field, validator, numeric_compatible)?;
1868                if !value.is_finite() {
1869                    return Err(BaseError::ConfigError(format!(
1870                        "表 {table} 的字段 {} 数值上限必须是有限数值",
1871                        field.name
1872                    )));
1873                }
1874                maximum = Some(maximum.map_or(*value, |current| current.min(*value)));
1875            }
1876            Validator::Email
1877            | Validator::EmailLoose
1878            | Validator::Phone
1879            | Validator::PhoneLoose
1880            | Validator::Url => {
1881                ensure_validator_type(table, field, validator, string_compatible)?;
1882            }
1883            Validator::Regex(pattern) => {
1884                ensure_validator_type(table, field, validator, string_compatible)?;
1885                #[cfg(feature = "validator")]
1886                regex::Regex::new(pattern).map_err(|error| {
1887                    BaseError::ConfigError(format!(
1888                        "表 {table} 的字段 {} 正则表达式无效: {error}",
1889                        field.name
1890                    ))
1891                })?;
1892                #[cfg(not(feature = "validator"))]
1893                return Err(BaseError::ConfigError(format!(
1894                    "表 {table} 的字段 {} 使用正则验证器 {pattern:?} 时必须启用 validator feature",
1895                    field.name,
1896                )));
1897            }
1898            Validator::Custom(_) => {}
1899        }
1900    }
1901
1902    if let (Some(min), Some(max)) = (min_length, max_length) {
1903        if min > max {
1904            return Err(BaseError::ConfigError(format!(
1905                "表 {table} 的字段 {} 最小长度不能大于最大长度",
1906                field.name
1907            )));
1908        }
1909    }
1910    if let (
1911        FieldType::String {
1912            max_length: storage_max,
1913        },
1914        Some(min),
1915    ) = (&field.field_type, min_length)
1916    {
1917        if min > *storage_max {
1918            return Err(BaseError::ConfigError(format!(
1919                "表 {table} 的字段 {} 最小长度不能超过字符串存储上限 {storage_max}",
1920                field.name
1921            )));
1922        }
1923    }
1924    if let (Some(min), Some(max)) = (minimum, maximum) {
1925        if min > max {
1926            return Err(BaseError::ConfigError(format!(
1927                "表 {table} 的字段 {} 数值下限不能大于上限",
1928                field.name
1929            )));
1930        }
1931    }
1932    Ok(())
1933}
1934
1935fn ensure_validator_type(
1936    table: &str,
1937    field: &FieldConfig,
1938    validator: &Validator,
1939    compatible: bool,
1940) -> Result<(), BaseError> {
1941    if compatible {
1942        return Ok(());
1943    }
1944    Err(BaseError::ConfigError(format!(
1945        "表 {table} 的字段 {} 类型不能使用{}验证器",
1946        field.name,
1947        validator.display_name()
1948    )))
1949}
1950
1951fn validate_audience(
1952    table: &str,
1953    field: &str,
1954    operation: &str,
1955    audience: &Audience,
1956) -> Result<(), BaseError> {
1957    if let Audience::Roles(roles) = audience {
1958        if roles.is_empty() || roles.iter().any(|role| role.trim().is_empty()) {
1959            return Err(BaseError::ConfigError(format!(
1960                "表 {table} 的字段 {field} 的{operation}角色不能为空"
1961            )));
1962        }
1963    }
1964    Ok(())
1965}
1966
1967fn set_unique_role(
1968    table: &str,
1969    role: &str,
1970    enabled: bool,
1971    field: &str,
1972    target: &mut Option<String>,
1973) -> Result<(), BaseError> {
1974    if !enabled {
1975        return Ok(());
1976    }
1977    if let Some(existing) = target {
1978        return Err(BaseError::ConfigError(format!(
1979            "表 {table} 的 {role} 语义重复定义在 {existing} 和 {field}"
1980        )));
1981    }
1982    *target = Some(field.to_string());
1983    Ok(())
1984}
1985
1986fn validate_index(
1987    table: &str,
1988    field_names: &HashSet<String>,
1989    index: &PendingIndex,
1990    index_names: &mut HashSet<String>,
1991) -> Result<(), BaseError> {
1992    if index.fields.is_empty() && index.expressions.is_empty() {
1993        return Err(BaseError::ConfigError(format!(
1994            "表 {table} 的索引字段与表达式不能同时为空"
1995        )));
1996    }
1997    let mut seen = HashSet::new();
1998    for field in &index.fields {
1999        if !field_names.contains(field) {
2000            return Err(BaseError::ConfigError(format!(
2001                "表 {table} 的索引字段不存在: {field}"
2002            )));
2003        }
2004        if !seen.insert(field) {
2005            return Err(BaseError::ConfigError(format!(
2006                "表 {table} 的索引重复引用字段: {field}"
2007            )));
2008        }
2009    }
2010    for expression in &index.expressions {
2011        validate_check_expression(table, "索引表达式", expression).map_err(|_| {
2012            BaseError::ConfigError(format!(
2013                "表 {table} 的索引表达式必须是单条、非空且长度受限的受信 SQL: {expression}"
2014            ))
2015        })?;
2016    }
2017    if let Some(predicate) = &index.predicate {
2018        validate_check_expression(table, "部分索引谓词", predicate).map_err(|_| {
2019            BaseError::ConfigError(format!(
2020                "表 {table} 的部分索引谓词必须是单条、非空且长度受限的受信 SQL: {predicate}"
2021            ))
2022        })?;
2023    }
2024    if !index.expressions.is_empty() && index.name.is_none() {
2025        return Err(BaseError::ConfigError(format!(
2026            "表 {table} 的表达式索引必须显式声明名称"
2027        )));
2028    }
2029    let prefix = if index.unique { "uk" } else { "idx" };
2030    let effective_name = index
2031        .name
2032        .clone()
2033        .unwrap_or_else(|| format!("{prefix}_{table}_{}", index.fields.join("_")));
2034    validate_identifier("索引", &effective_name)?;
2035    if !index_names.insert(effective_name.clone()) {
2036        return Err(BaseError::ConfigError(format!(
2037            "表 {table} 存在重复索引名: {effective_name}"
2038        )));
2039    }
2040    Ok(())
2041}
2042
2043fn validate_constraint_name(
2044    table: &str,
2045    name: &str,
2046    names: &mut HashSet<String>,
2047) -> Result<(), BaseError> {
2048    validate_identifier("约束", name)?;
2049    if !names.insert(name.to_string()) {
2050        return Err(BaseError::ConfigError(format!(
2051            "表 {table} 存在重复约束名: {name}"
2052        )));
2053    }
2054    Ok(())
2055}
2056
2057fn validate_check_expression(table: &str, name: &str, expression: &str) -> Result<(), BaseError> {
2058    let expression = expression.trim();
2059    if expression.is_empty()
2060        || expression.chars().count() > 2_048
2061        || [";", "--", "/*", "*/"]
2062            .iter()
2063            .any(|marker| expression.contains(marker))
2064        || !has_balanced_check_expression(expression)
2065    {
2066        return Err(BaseError::ConfigError(format!(
2067            "表 {table} 的 CHECK {name} 必须是单条、非空、长度受限且括号平衡的受信表达式"
2068        )));
2069    }
2070    Ok(())
2071}
2072
2073fn validate_foreign_key(
2074    table: &str,
2075    field_names: &HashSet<String>,
2076    foreign_key: &PendingForeignKey,
2077) -> Result<(), BaseError> {
2078    validate_identifier("外键目标表", &foreign_key.referenced_table)?;
2079    if foreign_key.columns.is_empty()
2080        || foreign_key.columns.len() != foreign_key.referenced_columns.len()
2081    {
2082        return Err(BaseError::ConfigError(format!(
2083            "表 {table} 的外键 {} 本地列与目标列必须非空且数量一致",
2084            foreign_key.name
2085        )));
2086    }
2087    let mut local = HashSet::new();
2088    let mut referenced = HashSet::new();
2089    for column in &foreign_key.columns {
2090        validate_identifier("外键列", column)?;
2091        if !field_names.contains(column) || !local.insert(column) {
2092            return Err(BaseError::ConfigError(format!(
2093                "表 {table} 的外键 {} 引用了缺失或重复的本地列 {column}",
2094                foreign_key.name
2095            )));
2096        }
2097    }
2098    for column in &foreign_key.referenced_columns {
2099        validate_identifier("外键目标列", column)?;
2100        if !referenced.insert(column) {
2101            return Err(BaseError::ConfigError(format!(
2102                "表 {table} 的外键 {} 重复引用目标列 {column}",
2103                foreign_key.name
2104            )));
2105        }
2106    }
2107    Ok(())
2108}
2109
2110fn field_json_schema(field: &FieldConfig) -> Value {
2111    let mut schema = Map::new();
2112    let mut min_length: Option<usize> = None;
2113    let mut max_length: Option<usize> = None;
2114    let mut minimum: Option<f64> = None;
2115    let mut maximum: Option<f64> = None;
2116    let mut patterns = Vec::new();
2117    let mut runtime_validators = Vec::new();
2118    match &field.field_type {
2119        FieldType::String {
2120            max_length: storage_max,
2121        } => {
2122            schema.insert("type".into(), json!("string"));
2123            max_length = Some(*storage_max);
2124        }
2125        FieldType::Text => {
2126            schema.insert("type".into(), json!("string"));
2127        }
2128        FieldType::Integer | FieldType::BigInt | FieldType::Timestamp => {
2129            schema.insert("type".into(), json!("integer"));
2130        }
2131        FieldType::Float | FieldType::Double => {
2132            schema.insert("type".into(), json!("number"));
2133        }
2134        FieldType::Decimal { precision, scale } => {
2135            schema.insert("type".into(), json!("string"));
2136            schema.insert("format".into(), json!("decimal"));
2137            schema.insert("x-precision".into(), json!(precision));
2138            schema.insert("x-scale".into(), json!(scale));
2139        }
2140        FieldType::Boolean => {
2141            schema.insert("type".into(), json!("boolean"));
2142        }
2143        FieldType::Date => {
2144            schema.insert("type".into(), json!("string"));
2145            schema.insert("format".into(), json!("date"));
2146        }
2147        FieldType::DateTime => {
2148            schema.insert("type".into(), json!("string"));
2149            schema.insert("format".into(), json!("date-time"));
2150        }
2151        FieldType::Json => {
2152            schema.insert("type".into(), json!(["object", "array"]));
2153        }
2154        FieldType::Enum { values } => {
2155            schema.insert("type".into(), json!("string"));
2156            schema.insert("enum".into(), json!(values));
2157        }
2158        FieldType::Uuid => {
2159            schema.insert("type".into(), json!("string"));
2160            schema.insert("format".into(), json!("uuid"));
2161        }
2162        FieldType::Bytes => {
2163            // Base64 文本;与 OpenAPI 的 `byte` format 对齐。
2164            schema.insert("type".into(), json!("string"));
2165            schema.insert("format".into(), json!("byte"));
2166        }
2167        FieldType::Array(element) => {
2168            schema.insert("type".into(), json!("array"));
2169            schema.insert("items".into(), storage_type_json_schema(element));
2170        }
2171    }
2172
2173    for validator in &field.validators {
2174        match validator {
2175            Validator::MinLength(value) => {
2176                min_length = Some(min_length.map_or(*value, |current| current.max(*value)));
2177            }
2178            Validator::MaxLength(value) => {
2179                max_length = Some(max_length.map_or(*value, |current| current.min(*value)));
2180            }
2181            Validator::Min(value) => {
2182                minimum = Some(minimum.map_or(*value, |current| current.max(*value)));
2183            }
2184            Validator::Max(value) => {
2185                maximum = Some(maximum.map_or(*value, |current| current.min(*value)));
2186            }
2187            Validator::Email => {
2188                #[cfg(feature = "validator")]
2189                patterns.push(r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$".to_string());
2190                #[cfg(not(feature = "validator"))]
2191                patterns.push("@".to_string());
2192            }
2193            Validator::EmailLoose => patterns.push("@".to_string()),
2194            Validator::Phone => {
2195                #[cfg(feature = "validator")]
2196                patterns.push(r"^\+?[1-9]\d{1,14}$".to_string());
2197                #[cfg(not(feature = "validator"))]
2198                patterns.push(r"^[0-9+\-]*$".to_string());
2199            }
2200            Validator::PhoneLoose => patterns.push(r"^[0-9\-]*$".to_string()),
2201            Validator::Url => patterns.push(r"^https?://".to_string()),
2202            Validator::Regex(pattern) => patterns.push(pattern.clone()),
2203            Validator::Custom(_) => runtime_validators.push("custom"),
2204        }
2205    }
2206
2207    if let Some(value) = min_length {
2208        schema.insert("minLength".into(), json!(value));
2209    }
2210    if let Some(value) = max_length {
2211        schema.insert("maxLength".into(), json!(value));
2212    }
2213    if let Some(value) = minimum {
2214        schema.insert("minimum".into(), json!(value));
2215    }
2216    if let Some(value) = maximum {
2217        schema.insert("maximum".into(), json!(value));
2218    }
2219    match patterns.as_slice() {
2220        [] => {}
2221        [pattern] => {
2222            schema.insert("pattern".into(), json!(pattern));
2223        }
2224        patterns => {
2225            schema.insert(
2226                "allOf".into(),
2227                Value::Array(
2228                    patterns
2229                        .iter()
2230                        .map(|pattern| json!({ "pattern": pattern }))
2231                        .collect(),
2232                ),
2233            );
2234        }
2235    }
2236    if !runtime_validators.is_empty() {
2237        schema.insert(
2238            "x-yang-runtime-validators".into(),
2239            json!(runtime_validators),
2240        );
2241    }
2242    if let Some(relation) = &field.relation {
2243        let relation_type = match relation.relation_type {
2244            RelationType::OneToOne => "one_to_one",
2245            RelationType::OneToMany => "one_to_many",
2246            RelationType::ManyToOne => "many_to_one",
2247            RelationType::ManyToMany => "many_to_many",
2248        };
2249        schema.insert(
2250            "x-yang-relation".into(),
2251            json!({
2252                "table": relation.table,
2253                "field": relation.field,
2254                "displayFields": relation.display_fields,
2255                "type": relation_type,
2256            }),
2257        );
2258    }
2259
2260    if !field.required {
2261        if let Some(field_types) = schema.get_mut("type") {
2262            match field_types {
2263                Value::String(field_type) => {
2264                    *field_types = json!([field_type.clone(), "null"]);
2265                }
2266                Value::Array(types) if !types.iter().any(|value| value == "null") => {
2267                    types.push(json!("null"));
2268                }
2269                _ => {}
2270            }
2271        }
2272        if let Some(Value::Array(values)) = schema.get_mut("enum") {
2273            values.push(Value::Null);
2274        }
2275    }
2276    if !field.display_name.is_empty() {
2277        schema.insert("title".into(), json!(field.display_name));
2278    }
2279    if let Some(default) = &field.default_value {
2280        schema.insert("default".into(), default.clone());
2281    }
2282    Value::Object(schema)
2283}
2284
2285/// 数组元素的 JSON Schema 存储类型(不含字段级校验器与权限元数据)。
2286fn storage_type_json_schema(field_type: &FieldType) -> Value {
2287    match field_type {
2288        FieldType::String { max_length } => json!({
2289            "type": "string",
2290            "maxLength": max_length,
2291        }),
2292        FieldType::Text => json!({"type": "string"}),
2293        FieldType::Uuid => json!({"type": "string", "format": "uuid"}),
2294        FieldType::Bytes => json!({"type": "string", "format": "byte"}),
2295        FieldType::Enum { values } => json!({"type": "string", "enum": values}),
2296        FieldType::Decimal { precision, scale } => json!({
2297            "type": "string",
2298            "format": "decimal",
2299            "x-precision": precision,
2300            "x-scale": scale,
2301        }),
2302        FieldType::Integer | FieldType::BigInt | FieldType::Timestamp => json!({"type": "integer"}),
2303        FieldType::Float | FieldType::Double => json!({"type": "number"}),
2304        FieldType::Boolean => json!({"type": "boolean"}),
2305        FieldType::Date => json!({"type": "string", "format": "date"}),
2306        FieldType::DateTime => json!({"type": "string", "format": "date-time"}),
2307        // 嵌套数组/JSON 元素在构建期已被拒绝,这里保持空 schema 作为兜底。
2308        FieldType::Json | FieldType::Array(_) => json!({}),
2309    }
2310}
2311
2312#[cfg(test)]
2313mod composite_primary_key_tests {
2314    use super::*;
2315
2316    #[test]
2317    fn table_without_primary_key_is_allowed() {
2318        let definition = Table::new("no_pk")
2319            .fields([Field::string("name", 64).required()])
2320            .build()
2321            .expect("无主键表定义应有效");
2322        assert!(definition.primary_keys().is_empty());
2323        assert_eq!(definition.primary_key(), "");
2324    }
2325
2326    #[test]
2327    fn composite_primary_key_keeps_all_columns() {
2328        let definition = Table::new("composite_pk")
2329            .fields([
2330                Field::bigint("tenant_id").required().primary_key(),
2331                Field::bigint("item_id").required().primary_key(),
2332                Field::string("name", 64),
2333            ])
2334            .build()
2335            .expect("复合主键表定义应有效");
2336        assert_eq!(definition.primary_key(), "tenant_id");
2337        assert_eq!(definition.primary_keys(), ["tenant_id", "item_id"]);
2338    }
2339}
2340
2341#[cfg(test)]
2342mod generated_expression_tests {
2343    use super::*;
2344
2345    fn generated_table(expression: &str) -> Result<TableDefinition, BaseError> {
2346        Table::new("generated_balance")
2347            .fields([
2348                Field::id("id"),
2349                Field::integer("price").required(),
2350                Field::string("name", 32),
2351                Field::bigint("total").generated(expression),
2352            ])
2353            .build()
2354    }
2355
2356    #[test]
2357    fn balanced_generated_expressions_pass() {
2358        generated_table("price * 2").expect("简单表达式应通过");
2359        generated_table("coalesce(price, 0)").expect("函数调用应通过");
2360        // 字符串字面量中的右括号不是语法括号。
2361        generated_table("coalesce(name, ')')").expect("字符串字面量含右括号应通过");
2362        // E 字符串中的反斜杠转义不破坏扫描。
2363        generated_table(r"coalesce(name, E'\')')").expect("E 字符串转义应通过");
2364    }
2365
2366    #[test]
2367    fn generated_expression_injection_is_rejected() {
2368        let error = generated_table("price) STORED, 注入 INTEGER")
2369            .expect_err("闭合外层括号的注入表达式必须拒绝");
2370        assert!(
2371            matches!(error, BaseError::ConfigError(ref message) if message.contains("生成列")),
2372            "实得错误: {error:?}"
2373        );
2374    }
2375}
2376
2377#[cfg(test)]
2378mod check_expression_tests {
2379    use super::*;
2380
2381    fn check_table(expression: &str) -> Result<TableDefinition, BaseError> {
2382        Table::new("check_balance")
2383            .fields([
2384                Field::id("id"),
2385                Field::integer("price").required(),
2386                Field::string("status", 32),
2387                Field::string("note", 64),
2388            ])
2389            .check_named("chk_balance", expression)
2390            .build()
2391    }
2392
2393    #[test]
2394    fn legal_check_expressions_pass() {
2395        check_table("price > 0").expect("简单表达式应通过");
2396        check_table("price > 0 AND status <> 'banned'").expect("字符串字面量应通过");
2397        check_table("(price > 0)").expect("成对分组括号应通过");
2398        check_table("`parent_id` > 0").expect("反引号标识符应通过");
2399        // MySQL 反斜杠转义字符串:右括号属于字符串,不是语法括号。
2400        check_table(r"note <> 'it\'s)'").expect("MySQL 反斜杠转义字符串应通过");
2401        // MySQL 反引号标识符内的括号不参与计数。
2402        check_table("`amount)` > 0").expect("反引号内的括号应通过");
2403        // MySQL # 注释内不成对括号不参与计数(PG 扫描侧会因缺右括号失败)。
2404        check_table("price > 0 # note (policy 2024\nAND status <> 'cancelled'")
2405            .expect("MySQL # 注释应通过");
2406        // PostgreSQL 美元引号内的括号不参与计数。
2407        check_table("$q$a)b$q$").expect("PostgreSQL 美元引号应通过");
2408        // PostgreSQL E 字符串的反斜杠转义不破坏扫描。
2409        check_table(r"note <> E'\')'").expect("PostgreSQL E 字符串应通过");
2410    }
2411
2412    #[test]
2413    fn check_expression_injection_is_rejected() {
2414        // RED: 现状仅黑名单 `; -- /* */`,该载荷可通过校验并在渲染时闭合
2415        // 外层 `CHECK (`,追加额外 DDL 子句。
2416        let error = check_table("price > 0), evil INT, CHECK (1=1")
2417            .expect_err("闭合外层括号的注入表达式必须拒绝");
2418        assert!(
2419            matches!(error, BaseError::ConfigError(ref message) if message.contains("CHECK")),
2420            "实得错误: {error:?}"
2421        );
2422    }
2423}