- 新 crate sspf-lowcode(纯计算,AR7 钉住不依赖 DB/HTTP):widget 把 54 种 jnpfKey 归成 11 类 (决定「怎么存、能不能接收入参」)/ form 解析控件树 / model 解析表结构 / validate 9 类诊断码 - DDL:base_visual_dev + base_visual_release 逐字对齐官方(21 → 23 张表) - MCP 3 个只读工具:form.list / form.describe / form.validate,后两个支持 inline JSON - 真实样例落盘为 fixture(官方初始化数据的「应收费用」:主表 6 字段 / 子表 8 字段) - 新增 lowcode-smoke.sh 8 条(含两条反自证:改坏 __vModel__ 必被抓、未知控件只 warn) - 影响:测试 306 → 344;十二闸全绿;三条真实方言已写进注释与测试
492 lines
17 KiB
Rust
492 lines
17 KiB
Rust
//! validate —— 表单 ↔ 模型**一致性校验**。
|
||
//!
|
||
//! ## 这是 P2 的验收核心
|
||
//!
|
||
//! PLAN 的 P2 出口是「基线平台导出的表单 JSON,不改一个字段能在 SSPF 上渲染 + 存取」。
|
||
//! 「能存取」的前提是**表单声明的字段,表里真有那些列** —— 这个前提在真实数据里
|
||
//! 经常不成立(改名不同步、删列没删控件、子表指向不存在的表)。
|
||
//!
|
||
//! 如果不校验就上动态 CRUD,症状是:**插入时少一列、查询时 sql 报错**,
|
||
//! 而错误信息是数据库给的(`column "f_xxx" does not exist`),AI 根本不知道该改哪。
|
||
//!
|
||
//! ⇒ 校验器把「数据库层的报错」提前成「设计态的明确诊断」。
|
||
//!
|
||
//! ## 诊断码表
|
||
//!
|
||
//! | 码 | 级别 | 含义 |
|
||
//! |---|---|---|
|
||
//! | `TABLE_NOT_IN_MODEL` | error | 表单引用的表没在 `f_tables_data` 里声明 |
|
||
//! | `COLUMN_NOT_IN_TABLE` | error | 表单字段在主表列里找不到对应列 |
|
||
//! | `SUBTABLE_COLUMN_MISSING` | error | 子表字段在子表列里找不到 |
|
||
//! | `REQUIRED_WITHOUT_COLUMN` | error | 必填字段没有对应列(必然存不进去) |
|
||
//! | `NO_MAIN_TABLE` | error | `f_tables_data` 里没有主表(`typeId=1`) |
|
||
//! | `UNKNOWN_WIDGET` | warn | 未知控件(已降级为文本) |
|
||
//! | `EMPTY_DATA_FIELDS` | warn | 表单没有任何数据字段 |
|
||
//! | `REQUIRED_NULLABLE` | warn | 必填字段对应的列允许 NULL(约束只在应用层) |
|
||
//! | `DISABLED_WIDGET_HAS_VALUE` | warn | 系统生成字段被设计成可编辑 |
|
||
//!
|
||
//! ## 为什么不用 error 就拦死
|
||
//!
|
||
//! `warn` 不阻断:未知控件降级后仍能读写,人工再修。
|
||
//! `error` 也不直接阻断存取 —— 有些库确实「设计稿先进、表后建」。
|
||
//! 但 `form.validate` 会把 error 明确报出来,让 AI 先修再存。
|
||
|
||
use serde_json::{json, Value};
|
||
|
||
use crate::form::FormSchema;
|
||
use crate::model::ModelSchema;
|
||
use crate::widget::WidgetKind;
|
||
|
||
/// 诊断级别。
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
pub enum Severity {
|
||
/// 会导致存取失败或写坏数据。
|
||
Error,
|
||
/// 能跑,但结果可能不符合预期。
|
||
Warn,
|
||
/// 纯提示。
|
||
Info,
|
||
}
|
||
|
||
impl Severity {
|
||
/// 稳定字符串。
|
||
pub fn as_str(self) -> &'static str {
|
||
match self {
|
||
Severity::Error => "error",
|
||
Severity::Warn => "warn",
|
||
Severity::Info => "info",
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 一条诊断。
|
||
#[derive(Debug, Clone, PartialEq)]
|
||
pub struct Diagnostic {
|
||
/// 机器可读码。
|
||
pub code: &'static str,
|
||
/// 级别。
|
||
pub severity: Severity,
|
||
/// 人话说明(含定位信息)。
|
||
pub message: String,
|
||
/// 出问题的位置(字段名 / 表名 / JSON 路径)。
|
||
pub path: String,
|
||
}
|
||
|
||
impl Diagnostic {
|
||
fn new(code: &'static str, severity: Severity, path: impl Into<String>, message: impl Into<String>) -> Self {
|
||
Self {
|
||
code,
|
||
severity,
|
||
path: path.into(),
|
||
message: message.into(),
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 校验报告。
|
||
#[derive(Debug, Clone, Default)]
|
||
pub struct Report {
|
||
/// 全部诊断(按发现顺序)。
|
||
pub diagnostics: Vec<Diagnostic>,
|
||
}
|
||
|
||
impl Report {
|
||
/// 是否没有任何 error(warn 不影响)。
|
||
pub fn ok(&self) -> bool {
|
||
!self
|
||
.diagnostics
|
||
.iter()
|
||
.any(|d| d.severity == Severity::Error)
|
||
}
|
||
|
||
/// 错误条数。
|
||
pub fn error_count(&self) -> usize {
|
||
self.diagnostics
|
||
.iter()
|
||
.filter(|d| d.severity == Severity::Error)
|
||
.count()
|
||
}
|
||
|
||
/// 警告条数。
|
||
pub fn warn_count(&self) -> usize {
|
||
self.diagnostics
|
||
.iter()
|
||
.filter(|d| d.severity == Severity::Warn)
|
||
.count()
|
||
}
|
||
|
||
/// 序列化成 MCP 工具的输出形状。
|
||
pub fn to_json(&self) -> Value {
|
||
json!({
|
||
"ok": self.ok(),
|
||
"errorCount": self.error_count(),
|
||
"warnCount": self.warn_count(),
|
||
"diagnostics": self.diagnostics.iter().map(|d| json!({
|
||
"code": d.code,
|
||
"severity": d.severity.as_str(),
|
||
"path": d.path,
|
||
"message": d.message,
|
||
})).collect::<Vec<_>>(),
|
||
})
|
||
}
|
||
|
||
fn push(&mut self, d: Diagnostic) {
|
||
self.diagnostics.push(d);
|
||
}
|
||
}
|
||
|
||
/// 校验「表单定义」与「模型定义」是否自洽。
|
||
pub fn validate(form: &FormSchema, model: &ModelSchema) -> Report {
|
||
let mut r = Report::default();
|
||
|
||
// ---- 1) 主表必须存在 ----
|
||
let Some(main) = model.main_table() else {
|
||
r.push(Diagnostic::new(
|
||
"NO_MAIN_TABLE",
|
||
Severity::Error,
|
||
"f_tables_data",
|
||
"模型里没有主表(typeId=1)—— 动态 CRUD 不知道该写哪张表",
|
||
));
|
||
return r;
|
||
};
|
||
|
||
// ---- 2) 表单引用的每张表都要有定义 ----
|
||
for t in form.table_names() {
|
||
if model.table(&t).is_none() {
|
||
r.push(Diagnostic::new(
|
||
"TABLE_NOT_IN_MODEL",
|
||
Severity::Error,
|
||
format!("table:{t}"),
|
||
format!(
|
||
"表单引用了表 `{t}`,但 f_tables_data 里没有它。\
|
||
典型原因:控件上的 tableName 改了但模型没同步"
|
||
),
|
||
));
|
||
}
|
||
}
|
||
|
||
// ---- 3) 主表字段 ↔ 主表列 ----
|
||
let main_fields = form.main_fields();
|
||
if main_fields.is_empty() {
|
||
r.push(Diagnostic::new(
|
||
"EMPTY_DATA_FIELDS",
|
||
Severity::Warn,
|
||
"fields",
|
||
"表单没有任何数据字段(全是布局/子表)—— 这个表单存不了主表数据",
|
||
));
|
||
}
|
||
|
||
for f in &main_fields {
|
||
let Some(col) = f.column_name() else {
|
||
// 系统生成字段可能没有 __vModel__,跳过(它们由后端填)
|
||
if f.widget != WidgetKind::SystemGenerated {
|
||
r.push(Diagnostic::new(
|
||
"COLUMN_NOT_IN_TABLE",
|
||
Severity::Error,
|
||
format!("field:{}", f.label),
|
||
format!(
|
||
"字段「{}」({})没有 __vModel__,无法映射到列",
|
||
f.label, f.jnpf_key
|
||
),
|
||
));
|
||
}
|
||
continue;
|
||
};
|
||
|
||
let found = main.column_by_name(&col);
|
||
if found.is_none() {
|
||
let code = if f.required {
|
||
"REQUIRED_WITHOUT_COLUMN"
|
||
} else {
|
||
"COLUMN_NOT_IN_TABLE"
|
||
};
|
||
r.push(Diagnostic::new(
|
||
code,
|
||
Severity::Error,
|
||
format!("field:{}", f.v_model),
|
||
format!(
|
||
"字段「{}」的 `{}` 映射到列 `{}`,但主表 `{}` 没有这一列。\
|
||
现有列:{}",
|
||
f.label,
|
||
f.v_model,
|
||
col,
|
||
main.table,
|
||
preview(&main.column_names())
|
||
),
|
||
));
|
||
continue;
|
||
}
|
||
|
||
// ---- 3b) 必填但列允许 NULL ----
|
||
if f.required {
|
||
if let Some(c) = found {
|
||
if c.allow_null {
|
||
r.push(Diagnostic::new(
|
||
"REQUIRED_NULLABLE",
|
||
Severity::Warn,
|
||
format!("field:{}", f.v_model),
|
||
format!(
|
||
"字段「{}」设计为必填,但列 `{col}` 允许 NULL —— \
|
||
约束只在应用层生效,直接写库仍可绕过",
|
||
f.label
|
||
),
|
||
));
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// ---- 4) 子表字段 ↔ 子表列 ----
|
||
for sub in form.sub_tables() {
|
||
let Some(table_name) = sub.table_name.as_deref().filter(|s| !s.is_empty()) else {
|
||
r.push(Diagnostic::new(
|
||
"TABLE_NOT_IN_MODEL",
|
||
Severity::Error,
|
||
format!("subtable:{}", sub.label),
|
||
format!("子表「{}」没有 tableName —— 不知道数据该进哪张表", sub.label),
|
||
));
|
||
continue;
|
||
};
|
||
let Some(t) = model.table(table_name) else {
|
||
// 已在第 2 步报过 TABLE_NOT_IN_MODEL,这里不重复
|
||
continue;
|
||
};
|
||
for c in &sub.children {
|
||
if !c.widget.occupies_column() {
|
||
continue;
|
||
}
|
||
let Some(col) = c.column_name() else {
|
||
continue;
|
||
};
|
||
if t.column_by_name(&col).is_none() {
|
||
r.push(Diagnostic::new(
|
||
"SUBTABLE_COLUMN_MISSING",
|
||
Severity::Error,
|
||
format!("subtable:{}:{}", table_name, c.v_model),
|
||
format!(
|
||
"子表「{}」的字段「{}」映射到列 `{}`,但表 `{}` 没有这一列",
|
||
sub.label, c.label, col, table_name
|
||
),
|
||
));
|
||
}
|
||
}
|
||
}
|
||
|
||
// ---- 5) 未知控件(降级警告)----
|
||
let unknown = form.unknown_widgets();
|
||
if !unknown.is_empty() {
|
||
let mut keys: Vec<&str> = unknown.iter().map(|n| n.jnpf_key.as_str()).collect();
|
||
keys.sort_unstable();
|
||
keys.dedup();
|
||
r.push(Diagnostic::new(
|
||
"UNKNOWN_WIDGET",
|
||
Severity::Warn,
|
||
"fields",
|
||
format!(
|
||
"{} 个未知控件({})已降级为文本 —— 能读写,但控件语义丢失;\
|
||
补齐 crates/sspf-lowcode/src/widget.rs 的 classify() 可精确支持",
|
||
unknown.len(),
|
||
keys.join(", ")
|
||
),
|
||
));
|
||
}
|
||
|
||
// ---- 6) 系统生成字段被设计成可编辑 ----
|
||
for n in form.all_nodes() {
|
||
if n.widget == WidgetKind::SystemGenerated && !n.no_show && n.required {
|
||
r.push(Diagnostic::new(
|
||
"DISABLED_WIDGET_HAS_VALUE",
|
||
Severity::Warn,
|
||
format!("field:{}", n.v_model),
|
||
format!(
|
||
"「{}」是系统生成控件({})却被标成必填 —— \
|
||
动态 CRUD 不会接收它的入参,必填校验会永远失败",
|
||
n.label, n.jnpf_key
|
||
),
|
||
));
|
||
}
|
||
}
|
||
|
||
r
|
||
}
|
||
|
||
/// 列名预览(最多 8 个,避免诊断信息过长)。
|
||
fn preview(cols: &[String]) -> String {
|
||
if cols.is_empty() {
|
||
return "(无列)".to_string();
|
||
}
|
||
let mut shown: Vec<&str> = cols.iter().take(8).map(String::as_str).collect();
|
||
let more = cols.len().saturating_sub(8);
|
||
let mut s = shown.join(", ");
|
||
shown.clear();
|
||
if more > 0 {
|
||
s.push_str(&format!(" …(还有 {more} 列)"));
|
||
}
|
||
s
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use serde_json::json;
|
||
|
||
fn model() -> ModelSchema {
|
||
ModelSchema::parse(&json!([
|
||
{
|
||
"table": "t_main", "tableName": "主表", "typeId": "1",
|
||
"fields": [
|
||
{"field":"F_Id","fieldName":"主键","dataType":"varchar","primaryKey":1,"allowNull":0},
|
||
{"field":"F_Title","fieldName":"标题","dataType":"varchar","allowNull":0},
|
||
{"field":"F_Memo","fieldName":"备注","dataType":"varchar","allowNull":1}
|
||
]
|
||
},
|
||
{
|
||
"table": "t_child", "tableName": "子表", "typeId": "0",
|
||
"fields": [{"field":"F_Item","fieldName":"项目","dataType":"varchar","allowNull":1}]
|
||
}
|
||
]))
|
||
.unwrap()
|
||
}
|
||
|
||
fn form_ok() -> FormSchema {
|
||
FormSchema::parse(&json!({
|
||
"formRef": "elForm",
|
||
"fields": [
|
||
{"__config__":{"jnpfKey":"input","tableName":"t_main","label":"标题","required":true},
|
||
"__vModel__":"F_Title"},
|
||
{"__config__":{"jnpfKey":"textarea","tableName":"t_main","label":"备注"},
|
||
"__vModel__":"F_Memo"},
|
||
{"__config__":{"jnpfKey":"table","layout":"rowFormItem","tableName":"t_child","label":"明细"},
|
||
"__vModel__":"tableField",
|
||
"children":[{"__config__":{"jnpfKey":"input","tableName":"t_child","label":"项目"},
|
||
"__vModel__":"F_Item"}]}
|
||
]
|
||
}))
|
||
.unwrap()
|
||
}
|
||
|
||
#[test]
|
||
fn clean_form_has_no_errors() {
|
||
let r = validate(&form_ok(), &model());
|
||
assert!(r.ok(), "不该有 error: {:?}", r.diagnostics);
|
||
assert_eq!(r.error_count(), 0);
|
||
}
|
||
|
||
/// 最常见的问题:控件改了名,模型没同步 ⇒ 列不存在。
|
||
#[test]
|
||
fn field_without_column_is_error_with_existing_columns() {
|
||
let f = FormSchema::parse(&json!({
|
||
"formRef": "elForm",
|
||
"fields": [{"__config__":{"jnpfKey":"input","tableName":"t_main","label":"不存在的字段"},
|
||
"__vModel__":"F_Ghost"}]
|
||
}))
|
||
.unwrap();
|
||
let r = validate(&f, &model());
|
||
assert!(!r.ok());
|
||
let d = r
|
||
.diagnostics
|
||
.iter()
|
||
.find(|d| d.code == "COLUMN_NOT_IN_TABLE")
|
||
.expect("应报 COLUMN_NOT_IN_TABLE");
|
||
assert!(d.message.contains("f_ghost"));
|
||
assert!(d.message.contains("f_title"), "要把现有列列出来,AI 才知道怎么改");
|
||
}
|
||
|
||
/// 必填字段没列 → 必须用更精确的码(REQUIRED_WITHOUT_COLUMN)。
|
||
#[test]
|
||
fn required_field_without_column_uses_specific_code() {
|
||
let f = FormSchema::parse(&json!({
|
||
"formRef": "elForm",
|
||
"fields": [{"__config__":{"jnpfKey":"input","tableName":"t_main","label":"必填幽灵","required":true},
|
||
"__vModel__":"F_Ghost"}]
|
||
}))
|
||
.unwrap();
|
||
let r = validate(&f, &model());
|
||
assert!(r
|
||
.diagnostics
|
||
.iter()
|
||
.any(|d| d.code == "REQUIRED_WITHOUT_COLUMN"));
|
||
}
|
||
|
||
#[test]
|
||
fn subtable_column_missing_is_reported() {
|
||
let f = FormSchema::parse(&json!({
|
||
"formRef": "elForm",
|
||
"fields": [
|
||
{"__config__":{"jnpfKey":"input","tableName":"t_main","label":"标题"},"__vModel__":"F_Title"},
|
||
{"__config__":{"jnpfKey":"table","layout":"rowFormItem","tableName":"t_child","label":"明细"},
|
||
"__vModel__":"tableField",
|
||
"children":[{"__config__":{"jnpfKey":"input","tableName":"t_child","label":"幽灵"},
|
||
"__vModel__":"F_Nope"}]}
|
||
]
|
||
}))
|
||
.unwrap();
|
||
let r = validate(&f, &model());
|
||
assert!(r
|
||
.diagnostics
|
||
.iter()
|
||
.any(|d| d.code == "SUBTABLE_COLUMN_MISSING"));
|
||
}
|
||
|
||
#[test]
|
||
fn table_missing_from_model_is_reported() {
|
||
let f = FormSchema::parse(&json!({
|
||
"formRef": "elForm",
|
||
"fields": [{"__config__":{"jnpfKey":"input","tableName":"t_other","label":"x"},"__vModel__":"F_X"}]
|
||
}))
|
||
.unwrap();
|
||
let r = validate(&f, &model());
|
||
assert!(r.diagnostics.iter().any(|d| d.code == "TABLE_NOT_IN_MODEL"));
|
||
}
|
||
|
||
#[test]
|
||
fn no_main_table_is_reported_once_and_stops() {
|
||
let m = ModelSchema::parse(&json!([
|
||
{"table":"t_child","typeId":"0","fields":[]}
|
||
]))
|
||
.unwrap();
|
||
let r = validate(&form_ok(), &m);
|
||
assert!(!r.ok());
|
||
assert_eq!(r.error_count(), 1, "只报一次,不继续刷错");
|
||
assert_eq!(r.diagnostics[0].code, "NO_MAIN_TABLE");
|
||
}
|
||
|
||
/// warn 不算失败 —— 未知控件降级后仍可用。
|
||
#[test]
|
||
fn unknown_widget_is_warn_not_error() {
|
||
let f = FormSchema::parse(&json!({
|
||
"formRef": "elForm",
|
||
"fields": [{"__config__":{"jnpfKey":"futureWidget","tableName":"t_main","label":"x"},
|
||
"__vModel__":"F_Title"}]
|
||
}))
|
||
.unwrap();
|
||
let r = validate(&f, &model());
|
||
assert!(r.ok(), "warn 不该让 ok=false");
|
||
assert_eq!(r.warn_count(), 1);
|
||
assert_eq!(r.diagnostics[0].code, "UNKNOWN_WIDGET");
|
||
}
|
||
|
||
#[test]
|
||
fn required_on_nullable_column_is_warn() {
|
||
// F_Memo 允许 NULL,但被设成必填
|
||
let f = FormSchema::parse(&json!({
|
||
"formRef": "elForm",
|
||
"fields": [{"__config__":{"jnpfKey":"input","tableName":"t_main","label":"备注","required":true},
|
||
"__vModel__":"F_Memo"}]
|
||
}))
|
||
.unwrap();
|
||
let r = validate(&f, &model());
|
||
assert!(r.ok());
|
||
assert!(r.diagnostics.iter().any(|d| d.code == "REQUIRED_NULLABLE"));
|
||
}
|
||
|
||
#[test]
|
||
fn report_serializes_to_tool_shape() {
|
||
let r = validate(&form_ok(), &model());
|
||
let j = r.to_json();
|
||
assert_eq!(j["ok"], true);
|
||
assert_eq!(j["errorCount"], 0);
|
||
assert!(j["diagnostics"].is_array());
|
||
}
|
||
}
|