把 src/backend/src/lowcode_{crud,ddl,check,seed}.rs 下沉到 crates/sspf-lowcode-exec/,
原路径全部变成 5 行转发壳 ⇒ CLI(--seed-lowcode-demo)与 MCP 适配器的调用路径零感知。
与 sspf-lowcode 的分工不变:前者纯计算(AR7 白名单不动),本 crate 是执行层
(连库 / 跑 SQL / 比对真实库列 / 事务 / 回写模型)。
依赖:sspf-lowcode + sspf-core + sspf-store + sspf-mcp + pglite-rs + chrono + serde_json
(比原计划多三个:pglite::ToSql/Error 是直接用的、now_iso() 用 chrono::Local::now()、JSON payload)
闸门改造:
- check-arch.sh 新增 AR13(两层:依赖白名单 + 源码不许 use sspf_pack_*)
- check-arch.sh 反自证 7→8(两处都注入:越界依赖 axum + 业务包引用,按路径分别验)
- check-boundary.sh 新增 LOWCODE_EXEC ⇒ CP1/CP2 纳入执行层真源
(反向验证:插 LEAK_PROBE ⇒ CP1 报红;还原后 11/11)
- check-contract-scan.py 不用改 —— 契约里零 lowcode 端点(低代码是 MCP 工具不是 HTTP 路由)
🔴 踩坑:改写时把 use crate::lowcode_ddl; 一并改成 use crate::ddl; ⇒ 编译不过。
教训:搬 crate 只改跨 crate 的前缀(crate::platform:: → sspf_core::),
模块名一律不动;文档内链([`crate::lowcode_crud`])也不能跟着改(改了就变死链)。
数字:cargo build 零警告;cargo test 695/0(与 M1 基线完全一致);
check-arch 17/17;--self-test 8/8;check-boundary 11/11;check-contract 10/10;
check-module 123/123;check-citations 4/4;check-naming 3/0/1;
verify.sh --smoke 14 步全绿(377.6s)
502 lines
18 KiB
Rust
502 lines
18 KiB
Rust
//! lowcode_check —— 写库**之前**的业务校验层(P2-b)。
|
||
//!
|
||
//! ## 为什么要有这一层
|
||
//!
|
||
//! 底层「设计稿列 vs 真实库列」的比对([`crate::lowcode_crud`])只回答
|
||
//! 「**能不能写**」(列在不在),不回答「**该不该写**」(值合不合法)。
|
||
//!
|
||
//! 基线平台在落库前有三道业务校验:
|
||
//!
|
||
//! | 校验 | 基线实现 | 本模块 |
|
||
//! |---|---|---|
|
||
//! | **业务主键** | `FormCheckUtils.checkBusinessKey()` | [`check_business_key`] |
|
||
//! | **必填** | `FormCheckUtils.checkForm()` 里的 `config.isRequired()` | 已在 `sspf-lowcode` 层(`MISSING_REQUIRED`) |
|
||
//! | **单行唯一** | `FormCheckUtils.checkForm()` 里的 `config.getUnique()` | [`check_unique_fields`] |
|
||
//!
|
||
//! ## 🔴 缺了会怎样
|
||
//!
|
||
//! 不做唯一性校验 ⇒ 库里能塞进两条「房间号相同」的记录 ⇒ 列表页看到重复数据,
|
||
//! 而用户以为系统拦住了。基线平台是拦住的 ⇒ **行为不一致 = 迁移没对齐**。
|
||
//!
|
||
//! ## 🔴 三条对齐口径(都来自 Java 源码,不是经验)
|
||
//!
|
||
//! 1. **只有 `jnpfKey == "input"` 且 `unique == true` 的字段才查唯一**
|
||
//! (Java `JnpfKeyConsts.COM_INPUT.equals(config.getJnpfKey())`)。
|
||
//! 下拉/日期/数字控件标了 `unique` 也**不查** —— 查多了会拦住基线允许的写入。
|
||
//! 2. **唯一性比对是「全表扫 + 排除自己」**,不是靠数据库 UNIQUE 约束。
|
||
//! Java 是 `SELECT ... WHERE col = ? AND pk <> ?`,然后看 `count > 0`。
|
||
//! 3. **业务主键是「组合唯一」**:清单里所有字段一起比;
|
||
//! 任一字段为空 ⇒ 该字段用 `IS NULL` 参与比较(Java `setEachCondition`)。
|
||
//!
|
||
//! ## 🔴 逻辑删除的行算不算重复
|
||
//!
|
||
//! 基线平台:逻辑删除的行**仍然占着**这个唯一值 —— 它只在判重时补了
|
||
//! `delete_mark IS NULL` 条件(`FormCheckUtils` 第 259–261 行),
|
||
//! 所以逻辑删除的行**不参与**判重。
|
||
//! ⇒ Rust 侧口径一致:查判重时带上 `delete_mark IS NULL`。
|
||
|
||
use serde_json::Value;
|
||
|
||
use sspf_lowcode::{check_identifier, lookup, FieldNode, FormSchema, ModelSchema};
|
||
|
||
use sspf_core::db::Db;
|
||
use sspf_mcp::adapter::ToolError;
|
||
|
||
/// 🔴 唯一性冲突的错误。
|
||
///
|
||
/// 基线平台的文案是 `字段名 + MsgCode.EXIST103`(≈「已存在」),
|
||
/// 这里给结构化的版本,AI 能据此自纠(改值 / 换 id)。
|
||
pub fn unique_conflict(label: &str, column: &str, value: &Value) -> ToolError {
|
||
let shown = match value {
|
||
Value::String(s) => s.clone(),
|
||
Value::Null => "NULL".to_string(),
|
||
other => other.to_string(),
|
||
};
|
||
ToolError::new(
|
||
"UNIQUE_CONSTRAINT_VIOLATED",
|
||
format!("字段「{label}」({column}) 的值 {shown} 已经存在了"),
|
||
)
|
||
.field(column)
|
||
.field("value")
|
||
.hint(format!(
|
||
"这个字段被设计成「单行唯一」;换一个值,或者先 data.query 看看哪条记录占着它"
|
||
))
|
||
.next(
|
||
"data.query",
|
||
serde_json::json!({ "enCode": "<功能编码>" }),
|
||
"查哪条记录占着这个值",
|
||
)
|
||
}
|
||
|
||
/// 🔴 业务主键冲突的错误。
|
||
pub fn business_key_conflict(tip: Option<&str>, columns: &[String]) -> ToolError {
|
||
let cols = columns.join(" + ");
|
||
let message = match tip {
|
||
Some(t) if !t.trim().is_empty() => t.to_string(),
|
||
_ => format!("业务主键({cols})已经存在了"),
|
||
};
|
||
ToolError::new("BUSINESS_KEY_VIOLATED", message)
|
||
.field("businessKey")
|
||
.hint(format!(
|
||
"这个功能启用了业务主键({cols})—— 这几个字段的组合必须唯一;\
|
||
换一个值,或先 data.query 查一下已有的组合"
|
||
))
|
||
.next(
|
||
"data.query",
|
||
serde_json::json!({ "enCode": "<功能编码>" }),
|
||
"查已有的业务主键组合",
|
||
)
|
||
}
|
||
|
||
/// 🔴 单行唯一校验(对齐 `FormCheckUtils.checkForm()` 的 unique 分支)。
|
||
///
|
||
/// - 只查 `jnpfKey == "input"` **且** `unique == true` 的字段;
|
||
/// - 比对范围:整张表(子表字段在**子表**里查,主表字段在**主表**里查);
|
||
/// - 排除自己:`record_id` 存在时把该行排除(更新场景);
|
||
/// - 逻辑删除的行不参与判重(`delete_mark IS NULL`)。
|
||
///
|
||
/// `record_id` 为 `None` ⇒ 新增场景(不排除任何行)。
|
||
pub async fn check_unique_fields(
|
||
db: &Db,
|
||
form: &FormSchema,
|
||
model: &ModelSchema,
|
||
payload: &Value,
|
||
record_id: Option<&str>,
|
||
) -> Result<(), ToolError> {
|
||
let fields = form.unique_fields();
|
||
if fields.is_empty() {
|
||
return Ok(());
|
||
}
|
||
let logical = form.logical_delete.unwrap_or(false);
|
||
|
||
for node in fields {
|
||
// 这个字段属于哪张表?
|
||
let (table_schema, column) = resolve_table_and_column(model, node).ok_or_else(|| {
|
||
ToolError::new(
|
||
"UNIQUE_CHECK_SKIPPED",
|
||
format!(
|
||
"字段「{}」({}) 标了唯一,但模型里找不到它对应的列 —— 跳过这一项的唯一校验",
|
||
node.label, node.v_model
|
||
),
|
||
)
|
||
.field(&node.v_model)
|
||
.hint("先 form.describe 看这个字段到底属于哪张表;模型与表单对不上")
|
||
})?;
|
||
|
||
let Some(raw) = lookup(payload, &node.v_model, &column) else {
|
||
// 没给值 ⇒ Java 那边 `o` 为空 ⇒ 用 `IS NULL` 判重。
|
||
// 但基线平台的 `unique` 语义是「这个值只能有一份」——
|
||
// 没给值时判重没意义(多数列 NOT NULL,落库时自然会报)。
|
||
// ⇒ 这里**跳过**:交给必填校验 / 数据库 NOT NULL 去管。
|
||
continue;
|
||
};
|
||
|
||
// Java `ObjectUtil.isEmpty(o) ? null : String.valueOf(o).trim()`
|
||
let value = match &raw {
|
||
Value::String(s) => {
|
||
let t = s.trim();
|
||
if t.is_empty() {
|
||
continue;
|
||
}
|
||
Value::String(t.to_string())
|
||
}
|
||
Value::Null => continue,
|
||
Value::Bool(b) => Value::String(b.to_string()),
|
||
Value::Number(n) => Value::String(n.to_string()),
|
||
_ => continue,
|
||
};
|
||
|
||
let mut params: Vec<String> = Vec::new();
|
||
let mut sql = format!(
|
||
"SELECT 1 FROM {} WHERE {} = $1",
|
||
table_schema.table, column
|
||
);
|
||
params.push(match &value {
|
||
Value::String(s) => s.clone(),
|
||
other => other.to_string(),
|
||
});
|
||
|
||
// 逻辑删除的行不参与判重(对齐 Java 的 `delete_mark IS NULL` 条件)。
|
||
if logical {
|
||
if let Some(dm) = delete_mark_column(table_schema) {
|
||
sql.push_str(&format!(" AND {} IS NULL", dm));
|
||
}
|
||
}
|
||
|
||
// 更新场景:排除自己那行。
|
||
if let Some(rid) = record_id {
|
||
if let Some(pk) = primary_key_column(table_schema) {
|
||
sql.push_str(&format!(" AND {} <> $2", pk));
|
||
params.push(rid.to_string());
|
||
}
|
||
}
|
||
|
||
sql.push_str(" LIMIT 1");
|
||
|
||
check_identifier("表名", &table_schema.table).map_err(ident_err)?;
|
||
check_identifier("列名", &column).map_err(ident_err)?;
|
||
|
||
// 🔴 参数个数必须与 SQL 里的占位符**一一对应**。
|
||
// 更新场景会多一个 `$2`(排除自己)⇒ 参数也要多一个。
|
||
// 少传 ⇒ pglite 报 `statement takes 2 parameters, 1 given`。
|
||
let refs: Vec<&(dyn pglite::ToSql + Sync)> = params
|
||
.iter()
|
||
.map(|s| s as &(dyn pglite::ToSql + Sync))
|
||
.collect();
|
||
let rows = db
|
||
.query_json_params(&sql, &refs)
|
||
.await
|
||
.map_err(|e| {
|
||
ToolError::new("DB_ERROR", format!("唯一性校验查库失败: {e}"))
|
||
.hint("先 schema.table.describe 看这张表的结构")
|
||
.retryable()
|
||
})?;
|
||
|
||
if !rows.is_empty() {
|
||
return Err(unique_conflict(&node.label, &column, &value));
|
||
}
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// 🔴 业务主键校验(对齐 `FormCheckUtils.checkBusinessKey()`)。
|
||
///
|
||
/// - 只在 `useBusinessKey == true` 且 `businessKeyList` 非空时生效;
|
||
/// - 清单里所有字段**一起**比(组合唯一);
|
||
/// - 任一字段没给值 ⇒ 该字段用 `IS NULL` 参与比较;
|
||
/// - 更新场景排除自己;
|
||
/// - 逻辑删除的行不参与判重。
|
||
pub async fn check_business_key(
|
||
db: &Db,
|
||
form: &FormSchema,
|
||
model: &ModelSchema,
|
||
payload: &Value,
|
||
record_id: Option<&str>,
|
||
) -> Result<(), ToolError> {
|
||
let Some(nodes) = form.business_key_fields() else {
|
||
return Ok(());
|
||
};
|
||
let Some(main) = model.main_table() else {
|
||
return Ok(());
|
||
};
|
||
let logical = form.logical_delete.unwrap_or(false);
|
||
|
||
// 把每个业务主键字段解析成「物理列 + 值」
|
||
let mut cols: Vec<String> = Vec::new();
|
||
let mut values: Vec<Option<String>> = Vec::new();
|
||
for node in &nodes {
|
||
let Some((tbl, col)) = resolve_table_and_column(model, node) else {
|
||
// 清单里的字段在模型里找不到 ⇒ 没法校验。
|
||
// 静默跳过会放过重复数据 ⇒ 明确报错,让 AI 知道设计稿有问题。
|
||
return Err(ToolError::new(
|
||
"BUSINESS_KEY_CHECK_FAILED",
|
||
format!(
|
||
"业务主键清单里的字段「{}」({}) 在模型里找不到对应的列 —— 无法校验",
|
||
node.label, node.v_model
|
||
),
|
||
)
|
||
.field(&node.v_model)
|
||
.hint("先 form.describe 看这个功能的字段与模型是否对得上"));
|
||
};
|
||
if !tbl.table.eq_ignore_ascii_case(&main.table) {
|
||
// 业务主键只在**主表**上判重(Java `checkBusinessKey` 用 mainTable)。
|
||
continue;
|
||
}
|
||
let v = lookup(payload, &node.v_model, &col)
|
||
.and_then(|v| match v {
|
||
Value::String(s) => {
|
||
let t = s.trim();
|
||
if t.is_empty() {
|
||
None
|
||
} else {
|
||
Some(t.to_string())
|
||
}
|
||
}
|
||
Value::Null => None,
|
||
Value::Bool(b) => Some(b.to_string()),
|
||
Value::Number(n) => Some(n.to_string()),
|
||
_ => None,
|
||
});
|
||
cols.push(col);
|
||
values.push(v);
|
||
}
|
||
if cols.is_empty() {
|
||
return Ok(());
|
||
}
|
||
|
||
check_identifier("表名", &main.table).map_err(ident_err)?;
|
||
|
||
// WHERE 条件:每个业务主键列 = ? (值为空则 IS NULL)
|
||
let mut where_parts: Vec<String> = Vec::new();
|
||
let mut params: Vec<String> = Vec::new();
|
||
for (i, (col, val)) in cols.iter().zip(values.iter()).enumerate() {
|
||
check_identifier("列名", col).map_err(ident_err)?;
|
||
match val {
|
||
Some(v) => {
|
||
params.push(v.clone());
|
||
where_parts.push(format!("{} = ${}", col, params.len()));
|
||
}
|
||
None => {
|
||
where_parts.push(format!("{} IS NULL", col));
|
||
}
|
||
}
|
||
let _ = i;
|
||
}
|
||
|
||
let mut sql = format!("SELECT 1 FROM {} WHERE {}", main.table, where_parts.join(" AND "));
|
||
|
||
if logical {
|
||
if let Some(dm) = delete_mark_column(main) {
|
||
sql.push_str(&format!(" AND {} IS NULL", dm));
|
||
}
|
||
}
|
||
if let Some(rid) = record_id {
|
||
if let Some(pk) = primary_key_column(main) {
|
||
params.push(rid.to_string());
|
||
sql.push_str(&format!(" AND {} <> ${}", pk, params.len()));
|
||
}
|
||
}
|
||
sql.push_str(" LIMIT 1");
|
||
|
||
let refs: Vec<&(dyn pglite::ToSql + Sync)> = params
|
||
.iter()
|
||
.map(|s| s as &(dyn pglite::ToSql + Sync))
|
||
.collect();
|
||
let rows = db
|
||
.query_json_params(&sql, &refs)
|
||
.await
|
||
.map_err(|e| {
|
||
ToolError::new("DB_ERROR", format!("业务主键校验查库失败: {e}"))
|
||
.hint("先 schema.table.describe 看这张表的结构")
|
||
.retryable()
|
||
})?;
|
||
|
||
if !rows.is_empty() {
|
||
return Err(business_key_conflict(
|
||
form.business_key_tip.as_deref(),
|
||
&cols,
|
||
));
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// 🔴 标识符非法时的错误转换。
|
||
fn ident_err(e: sspf_lowcode::SqlError) -> ToolError {
|
||
ToolError::new(e.code(), e.message()).hint("表名/列名只能含字母、数字、下划线")
|
||
}
|
||
|
||
/// 🔴 找字段属于哪张表 + 它对应的物理列名。
|
||
///
|
||
/// 主表字段 → 主表;子表字段 → 子表(靠 `relationTable`)。
|
||
fn resolve_table_and_column<'a>(
|
||
model: &'a ModelSchema,
|
||
node: &FieldNode,
|
||
) -> Option<(&'a sspf_lowcode::TableSchema, String)> {
|
||
// 子表字段:靠 `relationTable`(`tableName` 对子表字段不可信 —— 见 form.rs 注释)
|
||
if let Some(rel) = &node.relation_table {
|
||
if let Some(t) = model.table(rel) {
|
||
if let Some(col) = column_for(t, node) {
|
||
return Some((t, col));
|
||
}
|
||
}
|
||
}
|
||
// 主表字段:靠 `tableName`;退回到主表
|
||
if let Some(tn) = &node.table_name {
|
||
if let Some(t) = model.table(tn) {
|
||
if let Some(col) = column_for(t, node) {
|
||
return Some((t, col));
|
||
}
|
||
}
|
||
}
|
||
let main = model.main_table()?;
|
||
let col = column_for(main, node)?;
|
||
Some((main, col))
|
||
}
|
||
|
||
/// 🔴 在一张表的列定义里找这个字段的物理列名。
|
||
fn column_for(table: &sspf_lowcode::TableSchema, node: &FieldNode) -> Option<String> {
|
||
// 先按 `__vModel__` 精确匹配
|
||
if let Some(c) = table.column_by_field(&node.v_model) {
|
||
if let Some(col) = c.resolved_column() {
|
||
return Some(col);
|
||
}
|
||
}
|
||
// 再按「剥前缀 + 转小写」推导
|
||
sspf_lowcode::v_model_to_column(&node.v_model)
|
||
}
|
||
|
||
/// 🔴 主键列(排除租户列 —— Java `checkBusinessKey` 的口径)。
|
||
fn primary_key_column(table: &sspf_lowcode::TableSchema) -> Option<String> {
|
||
table
|
||
.primary_keys()
|
||
.into_iter()
|
||
.find(|c| !c.contains("f_tenant_id"))
|
||
}
|
||
|
||
/// 🔴 删除标记列(逻辑删除时用来排除已删行)。
|
||
fn delete_mark_column(table: &sspf_lowcode::TableSchema) -> Option<String> {
|
||
table
|
||
.fields
|
||
.iter()
|
||
.find(|c| {
|
||
let f = c.field.to_lowercase();
|
||
f.contains("f_delete_mark") || f == "delete_mark"
|
||
})
|
||
.and_then(|c| c.resolved_column())
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use serde_json::json;
|
||
|
||
const FORM: &str = r#"{
|
||
"logicalDelete": true,
|
||
"useBusinessKey": true,
|
||
"businessKeyList": ["F_Code"],
|
||
"businessKeyTip": "业务编码已存在",
|
||
"fields": [
|
||
{
|
||
"__config__": {
|
||
"jnpfKey": "input", "layout": "colFormItem", "label": "房间号",
|
||
"tableName": "biz_main", "required": true, "unique": true
|
||
},
|
||
"__vModel__": "F_Room"
|
||
},
|
||
{
|
||
"__config__": {
|
||
"jnpfKey": "input", "layout": "colFormItem", "label": "业务编码",
|
||
"tableName": "biz_main", "required": false
|
||
},
|
||
"__vModel__": "F_Code"
|
||
},
|
||
{
|
||
"__config__": {
|
||
"jnpfKey": "inputNumber", "layout": "colFormItem", "label": "数量",
|
||
"tableName": "biz_main", "unique": true
|
||
},
|
||
"__vModel__": "F_Qty"
|
||
}
|
||
]
|
||
}"#;
|
||
|
||
const MODEL: &str = r#"[
|
||
{
|
||
"table": "biz_main", "tableName": "主表", "typeId": "1",
|
||
"fields": [
|
||
{ "field": "F_Id", "fieldName": "主键", "dataType": "varchar",
|
||
"primaryKey": 1, "allowNull": false },
|
||
{ "field": "F_Tenant_Id", "fieldName": "租户", "dataType": "varchar",
|
||
"primaryKey": 1, "allowNull": false },
|
||
{ "field": "F_Room", "fieldName": "房间号", "dataType": "varchar" },
|
||
{ "field": "F_Code", "fieldName": "业务编码", "dataType": "varchar" },
|
||
{ "field": "F_Qty", "fieldName": "数量", "dataType": "int4" },
|
||
{ "field": "F_Delete_Mark", "fieldName": "删除标记", "dataType": "int4" }
|
||
]
|
||
}
|
||
]"#;
|
||
|
||
fn form() -> FormSchema {
|
||
FormSchema::parse(&json!({
|
||
"fields": serde_json::from_str::<Value>(FORM).unwrap()["fields"].clone(),
|
||
"logicalDelete": true,
|
||
"useBusinessKey": true,
|
||
"businessKeyList": ["F_Code"],
|
||
"businessKeyTip": "业务编码已存在",
|
||
}))
|
||
.unwrap()
|
||
}
|
||
|
||
fn model() -> ModelSchema {
|
||
ModelSchema::parse(&serde_json::from_str::<Value>(MODEL).unwrap()).unwrap()
|
||
}
|
||
|
||
/// 🔴 只有 `input` + `unique` 才参与判重 —— 数字控件标了 unique 也不查。
|
||
#[test]
|
||
fn only_input_with_unique_is_checked() {
|
||
let f = form();
|
||
let uniq = f.unique_fields();
|
||
assert_eq!(uniq.len(), 1, "应该只有 F_Room 一个字段参与唯一校验");
|
||
assert_eq!(uniq[0].v_model, "F_Room");
|
||
}
|
||
|
||
/// 🔴 业务主键清单能被解析成字段。
|
||
#[test]
|
||
fn business_key_fields_are_resolved() {
|
||
let f = form();
|
||
let bk = f.business_key_fields().expect("应该启用业务主键");
|
||
assert_eq!(bk.len(), 1);
|
||
assert_eq!(bk[0].v_model, "F_Code");
|
||
}
|
||
|
||
/// 🔴 没启用业务主键 ⇒ 不校验。
|
||
#[test]
|
||
fn business_key_disabled_returns_none() {
|
||
let f = FormSchema::parse(&json!({
|
||
"fields": serde_json::from_str::<Value>(FORM).unwrap()["fields"].clone(),
|
||
}))
|
||
.unwrap();
|
||
assert!(f.business_key_fields().is_none());
|
||
}
|
||
|
||
/// 🔴 主键列要排除租户列。
|
||
#[test]
|
||
fn primary_key_excludes_tenant() {
|
||
let m = model();
|
||
let main = m.main_table().unwrap();
|
||
assert_eq!(
|
||
primary_key_column(main).as_deref(),
|
||
Some("f_id"),
|
||
"租户列也是 primaryKey=1,但不能被当成主键"
|
||
);
|
||
}
|
||
|
||
/// 🔴 删除标记列能被认出来。
|
||
#[test]
|
||
fn delete_mark_column_is_found() {
|
||
let m = model();
|
||
let main = m.main_table().unwrap();
|
||
assert_eq!(delete_mark_column(main).as_deref(), Some("f_delete_mark"));
|
||
}
|
||
}
|