refactor(arch): M5 低代码执行层下沉 —— 4 模块 / 2,674 行迁入 sspf-lowcode-exec
把 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)
This commit is contained in:
1 parent
e821770f58
commit
98b93967da
18 files changed
+3006
-2698
No files matched your search
@@ -62,6 +62,9 @@ sspf-compat-online_dev = { path = "../../crates/sspf-compat-online_dev" }
|
||||
sspf-mcp = { path = "../../crates/sspf-mcp" }
|
||||
# 低代码元数据引擎(纯计算:解析/校验/SQL 生成)
|
||||
sspf-lowcode = { path = "../../crates/sspf-lowcode" }
|
||||
# 🔴 **低代码执行层**(M5)—— 连库 / 跑 SQL / 比对真实库列 / 事务 / 回写模型。
|
||||
# `src/backend/src/lowcode_*.rs` 现在只是转发壳 ⇒ CLI 与 MCP 适配器的调用路径零感知。
|
||||
sspf-lowcode-exec = { path = "../../crates/sspf-lowcode-exec" }
|
||||
|
||||
# 业务包装载器(L2 静态:读清单 / 校验 / 收集声明)—— 不认识 axum
|
||||
sspf-plugin = { path = "../../crates/sspf-plugin" }
|
||||
|
||||
@@ -1,501 +1,5 @@
|
||||
//! 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`。
|
||||
//! lowcode_check —— **转发壳**:真源在 [`sspf_lowcode_exec::lowcode_check`](M5 低代码执行层下沉)。
|
||||
//! 🔴 只做转发、不含实现;CLI(`--seed-lowcode-demo`)与 MCP 适配器的调用路径不用改。
|
||||
//! 为什么留壳、闸门怎么改:见 `docs/CRATES-MIGRATION.md` §4 M5。
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use sspf_lowcode::{check_identifier, lookup, FieldNode, FormSchema, ModelSchema};
|
||||
|
||||
use crate::platform::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"));
|
||||
}
|
||||
}
|
||||
pub use sspf_lowcode_exec::lowcode_check::*;
|
||||
+4
-1239
File diff suppressed because it is too large.
Load diff
@@ -1,430 +1,5 @@
|
||||
//! lowcode_ddl —— 内核侧的**动态建表执行层**(P2-b 的最后一块)。
|
||||
//!
|
||||
//! ## 分工(与 [`crate::lowcode_crud`] 同款)
|
||||
//!
|
||||
//! | 层 | 位置 | 干什么 |
|
||||
//! |---|---|---|
|
||||
//! | **DDL 生成** | `sspf-lowcode::ddl`(纯计算,AR7) | 出 `CREATE TABLE` 文本 + 回写后的模型 |
|
||||
//! | **执行** | 本文件(内核) | 连库、跑 DDL、回写 `f_tables_data` |
|
||||
//!
|
||||
//! ## 🔴 三步闭环(缺一不可)
|
||||
//!
|
||||
//! ```text
|
||||
//! 1. plan_create() → CREATE TABLE 文本(主表在前,子表随后)
|
||||
//! 2. 执行 DDL → 真实库里有表了
|
||||
//! 3. rewrite_model() → 把真实表结构回写进 f_tables_data
|
||||
//! ```
|
||||
//!
|
||||
//! ## 🔴 第 3 步为什么**不是可选的**
|
||||
//!
|
||||
//! 基线平台 `VisualDevTableCre.tableList()` 建完表后会用**建表清单**重新组装
|
||||
//! `TableModel` 再写回 `f_tables_data`:
|
||||
//!
|
||||
//! ```java
|
||||
//! this.tableModel(tableModelList, datableList, tableName, table, true, tableField, relationField);
|
||||
//! ...
|
||||
//! entity.setVisualTables(JsonUtil.getObjectToString(tableModelList));
|
||||
//! ```
|
||||
//!
|
||||
//! ⇒ 建表后的模型**含平台追加的系统列**(`f_tenant_id` / `f_delete_mark` …)。
|
||||
//!
|
||||
//! 不回写的后果(本项目已真实踩到):
|
||||
//!
|
||||
//! | 现象 | 根因 |
|
||||
//! |---|---|
|
||||
//! | 逻辑删除报 `LOGICAL_DELETE_UNSUPPORTED` | CRUD 层在**模型**里找 `f_delete_mark`,找不到 |
|
||||
//! | 「设计稿 vs 真实库」列比对永远对不上 | 模型少列、真实库多列 |
|
||||
//! | `f_tenant_id` 不被写 | 租户列在模型里缺失 |
|
||||
//!
|
||||
//! ## 🔴 幂等
|
||||
//!
|
||||
//! 基线平台 `DbTableServiceImpl.createTable()` 会先检查表是否已存在,
|
||||
//! 存在则直接返回(不重复建)。本模块同理:
|
||||
//!
|
||||
//! - 表已存在 ⇒ **不报错**,跳过 DDL,但**仍然回写模型**
|
||||
//! (回写是幂等的,且让「设计稿落后于真实库」自动修复)。
|
||||
//! - 表已存在但**列结构不同** ⇒ 报 `TABLE_ALREADY_EXISTS_DIFFERENT`,
|
||||
//! 明确告诉调用方「不是同一次建表的结果」,让人去核对而不是硬改。
|
||||
//!
|
||||
//! ## 🔴 只在开发期可用
|
||||
//!
|
||||
//! 建表是**破坏性**操作(会改真实库结构)。本模块提供 `Profile::Dev` 闸门,
|
||||
//! 生产档直接拒绝 —— 见 [`create_tables`].
|
||||
//! lowcode_ddl —— **转发壳**:真源在 [`sspf_lowcode_exec::lowcode_ddl`](M5 低代码执行层下沉)。
|
||||
//! 🔴 只做转发、不含实现;CLI(`--seed-lowcode-demo`)与 MCP 适配器的调用路径不用改。
|
||||
//! 为什么留壳、闸门怎么改:见 `docs/CRATES-MIGRATION.md` §4 M5。
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use sspf_lowcode::{
|
||||
plan_create, rewrite_model, CreatePlan, DdlError, DdlOptions, FormSchema, ModelSchema,
|
||||
};
|
||||
use sspf_mcp::adapter::ToolError;
|
||||
|
||||
use crate::platform::db::Db;
|
||||
|
||||
/// 建表的结果。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CreateTablesOutcome {
|
||||
/// 建出来的表(主表在前)。
|
||||
pub tables: Vec<String>,
|
||||
/// 哪些表是**已存在**因而跳过的。
|
||||
pub skipped: Vec<String>,
|
||||
/// 回写后的模型(`f_tables_data` 的新值)。
|
||||
pub model: Value,
|
||||
/// 诊断信息。
|
||||
pub notes: Vec<String>,
|
||||
/// 实际执行的 DDL(dry-run 时给调用方看)。
|
||||
pub ddl: Vec<String>,
|
||||
/// 是否只是演练(没建表、没回写)。
|
||||
pub dry_run: bool,
|
||||
}
|
||||
|
||||
impl CreateTablesOutcome {
|
||||
/// 一共几张表。
|
||||
pub fn table_count(&self) -> usize {
|
||||
self.tables.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// 🔴 把 DDL 错误转成结构化工具错误。
|
||||
pub fn ddl_err(e: DdlError) -> ToolError {
|
||||
let mut t = ToolError::new(e.code(), e.message());
|
||||
match &e {
|
||||
DdlError::NoMainTable => {
|
||||
t = t.hint("这个功能定义里没有主表(typeId=1)—— 设计稿不完整");
|
||||
}
|
||||
DdlError::IllegalIdentifier { kind, value } => {
|
||||
t = t
|
||||
.field(*kind)
|
||||
.hint(format!(
|
||||
"{kind}「{value}」含非法字符;表名/列名只允许字母、数字、下划线,且不能以数字开头"
|
||||
))
|
||||
.next("form.describe", json!({ "enCode": "<功能编码>" }), "看设计稿里的表名");
|
||||
}
|
||||
DdlError::DuplicateColumn { table, column } => {
|
||||
t = t
|
||||
.field(column)
|
||||
.hint(format!(
|
||||
"表 {table} 里两列推出同一个物理列名 {column};检查模型里是不是有同义字段"
|
||||
));
|
||||
}
|
||||
DdlError::UnsupportedType {
|
||||
table,
|
||||
column,
|
||||
data_type,
|
||||
} => {
|
||||
t = t
|
||||
.field(column)
|
||||
.hint(format!(
|
||||
"表 {table} 的列 {column} 类型「{data_type}」还没支持;\
|
||||
改这个字段的类型,或在 sspf-lowcode 的 map_type() 里补上"
|
||||
));
|
||||
}
|
||||
DdlError::InvalidLength {
|
||||
table,
|
||||
column,
|
||||
length,
|
||||
} => {
|
||||
t = t
|
||||
.field(column)
|
||||
.hint(format!(
|
||||
"表 {table} 的列 {column} 长度「{length}」不合法;\
|
||||
varchar 填数字,decimal 填「精度,标度」如 18,2"
|
||||
));
|
||||
}
|
||||
DdlError::NoPrimaryKey(table) => {
|
||||
t = t
|
||||
.hint(format!(
|
||||
"表 {table} 的模型里没有 primaryKey=1 的列 —— 建不出主键,先在设计稿里标主键"
|
||||
));
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
/// 🔴 表是否已存在。
|
||||
pub async fn table_exists(db: &Db, table: &str) -> Result<bool, ToolError> {
|
||||
let rows = db
|
||||
.query_json_params(
|
||||
"SELECT 1 AS \"x\" FROM information_schema.tables \
|
||||
WHERE table_name = $1 LIMIT 1",
|
||||
&[&table.to_string()],
|
||||
)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
Ok(!rows.is_empty())
|
||||
}
|
||||
|
||||
/// 🔴 真实库里某张表的列(按序)。
|
||||
pub async fn real_columns(db: &Db, table: &str) -> Result<Vec<String>, ToolError> {
|
||||
let rows = db
|
||||
.query_json_params(
|
||||
"SELECT column_name AS \"name\" FROM information_schema.columns \
|
||||
WHERE table_name = $1 ORDER BY ordinal_position",
|
||||
&[&table.to_string()],
|
||||
)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
Ok(rows
|
||||
.iter()
|
||||
.map(|r| r["name"].as_str().unwrap_or_default().to_string())
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// 🔴 执行一次动态建表(**幂等**)。
|
||||
///
|
||||
/// ## 参数
|
||||
///
|
||||
/// - `db`:真实库连接;
|
||||
/// - `model`:**建表前**的模型(`f_tables_data`);
|
||||
/// - `form`:表单定义(决定 `logicalDelete` / `primaryKeyPolicy`);
|
||||
/// - `dry_run`:只生成 DDL 与回写后的模型,**不建表、不回写**。
|
||||
///
|
||||
/// ## 🔴 幂等语义
|
||||
///
|
||||
/// 表已存在 ⇒ 跳过 DDL,但**仍回写模型**(回写是幂等的)。
|
||||
/// 列结构不一致 ⇒ 报 `TABLE_EXISTS_DIFFERENT`,让人去核对。
|
||||
pub async fn create_tables(
|
||||
db: &Db,
|
||||
model: &ModelSchema,
|
||||
form: &FormSchema,
|
||||
dry_run: bool,
|
||||
) -> Result<CreateTablesOutcome, ToolError> {
|
||||
// 🔴 建表选项来自**表单**(基线平台同款:`VisualTableModel` 从 `FormDataModel` 取)。
|
||||
let options = DdlOptions {
|
||||
logical_delete: form.logical_delete.unwrap_or(false),
|
||||
with_comments: false,
|
||||
primary_key_policy: form.primary_key_policy.unwrap_or(1),
|
||||
};
|
||||
|
||||
let plan = plan_create(model, &options).map_err(ddl_err)?;
|
||||
let ddl = plan.render();
|
||||
|
||||
// ---- 回写后的模型(纯计算,先算好;dry-run 也要给)----
|
||||
let rewritten = rewrite_model(model, &plan);
|
||||
|
||||
let mut tables = Vec::new();
|
||||
let mut skipped = Vec::new();
|
||||
let mut notes = Vec::new();
|
||||
|
||||
if dry_run {
|
||||
for t in plan.all() {
|
||||
tables.push(t.table.clone());
|
||||
}
|
||||
return Ok(CreateTablesOutcome {
|
||||
tables,
|
||||
skipped,
|
||||
model: rewritten,
|
||||
notes: vec!["dry-run:没有建表,也没有回写模型".to_string()],
|
||||
ddl,
|
||||
dry_run: true,
|
||||
});
|
||||
}
|
||||
|
||||
// ---- 逐表执行(主表在前,子表随后)----
|
||||
for t in plan.all() {
|
||||
if table_exists(db, &t.table).await? {
|
||||
// 🔴 已存在 ⇒ 跳过 DDL,但**核对列**。
|
||||
let actual = real_columns(db, &t.table).await?;
|
||||
let expected = t.column_names();
|
||||
if actual != expected {
|
||||
return Err(table_exists_different(&t.table, &expected, &actual));
|
||||
}
|
||||
skipped.push(t.table.clone());
|
||||
notes.push(format!(
|
||||
"表 {} 已存在且列结构一致 —— 跳过建表(幂等)",
|
||||
t.table
|
||||
));
|
||||
continue;
|
||||
}
|
||||
|
||||
let sql = t.render();
|
||||
db.exec(&sql)
|
||||
.await
|
||||
.map_err(|e| create_failed(&t.table, &e.to_string(), &sql))?;
|
||||
tables.push(t.table.clone());
|
||||
}
|
||||
|
||||
Ok(CreateTablesOutcome {
|
||||
tables,
|
||||
skipped,
|
||||
model: rewritten,
|
||||
notes,
|
||||
ddl,
|
||||
dry_run: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// 🔴 表已存在但列结构不一致。
|
||||
fn table_exists_different(table: &str, expected: &[String], actual: &[String]) -> ToolError {
|
||||
let missing: Vec<&str> = expected
|
||||
.iter()
|
||||
.filter(|c| !actual.contains(c))
|
||||
.map(|s| s.as_str())
|
||||
.collect();
|
||||
let extra: Vec<&str> = actual
|
||||
.iter()
|
||||
.filter(|c| !expected.contains(c))
|
||||
.map(|s| s.as_str())
|
||||
.collect();
|
||||
|
||||
let mut msg = format!("表 {table} 已存在,但列结构和设计稿对不上");
|
||||
if !missing.is_empty() {
|
||||
msg.push_str(&format!(";设计稿声明但库里没有:{}", missing.join(", ")));
|
||||
}
|
||||
if !extra.is_empty() {
|
||||
msg.push_str(&format!(";库里有但设计稿没声明:{}", extra.join(", ")));
|
||||
}
|
||||
|
||||
ToolError::new("TABLE_EXISTS_DIFFERENT", msg)
|
||||
.field("table")
|
||||
.hint(
|
||||
"这张表不是当前设计稿建出来的(可能是手写的、或改过设计稿没重建表)。\
|
||||
改设计稿请先重建表,或手动对齐库里的列 —— 别让工具替你猜",
|
||||
)
|
||||
.next(
|
||||
"schema.table.describe",
|
||||
json!({ "table": table }),
|
||||
"看这张表现在到底有哪些列",
|
||||
)
|
||||
}
|
||||
|
||||
/// 🔴 建表失败。
|
||||
fn create_failed(table: &str, err: &str, sql: &str) -> ToolError {
|
||||
ToolError::new("CREATE_TABLE_FAILED", format!("建表 {table} 失败:{err}"))
|
||||
.field("table")
|
||||
.hint("看下面的 DDL 定位问题;最常见是标识符非法或类型不匹配")
|
||||
.hint(format!("执行的 DDL:{}", sql))
|
||||
.next(
|
||||
"form.describe",
|
||||
json!({ "enCode": "<功能编码>" }),
|
||||
"核对设计稿里的表名与列",
|
||||
)
|
||||
}
|
||||
|
||||
/// 🔴 DB 错误转工具错误。
|
||||
fn db_err(e: pglite::Error) -> ToolError {
|
||||
ToolError::new("DB_ERROR", format!("数据库错误:{e}"))
|
||||
.hint("先确认数据库连接正常;这个错误通常来自 SQL 或连接配置")
|
||||
}
|
||||
|
||||
/// 🔴 把回写后的模型写回 `base_visual_dev.f_tables_data`。
|
||||
///
|
||||
/// ## 🔴 为什么**只**写 `f_tables_data`
|
||||
///
|
||||
/// 基线平台 `VisualdevServiceImpl.createTable()` 建表后写的是
|
||||
/// `entity.setVisualTables(...)` —— 也就是 `f_tables_data` 一列。
|
||||
/// `f_column_data`(列表列)与 `f_form_data`(控件树)由前端另行维护,
|
||||
/// 建表不碰它们。
|
||||
pub async fn write_back_model(
|
||||
db: &Db,
|
||||
visualdev_id: &str,
|
||||
model_json: &Value,
|
||||
) -> Result<(), ToolError> {
|
||||
let text = serde_json::to_string(model_json).map_err(|e| {
|
||||
ToolError::new("MODEL_SERIALIZE_FAILED", format!("模型序列化失败:{e}"))
|
||||
})?;
|
||||
|
||||
// 🔴 先确认记录存在 —— `exec_params` 不返回影响行数
|
||||
// (pglite 0.2.7 没有这个能力),所以只能先查再写。
|
||||
let exists = db
|
||||
.query_json_params(
|
||||
"SELECT 1 AS \"x\" FROM base_visual_dev WHERE f_id = $1 LIMIT 1",
|
||||
&[&visualdev_id.to_string()],
|
||||
)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
if exists.is_empty() {
|
||||
return Err(ToolError::new(
|
||||
"FORM_NOT_FOUND",
|
||||
format!("低代码功能不存在:{visualdev_id}"),
|
||||
)
|
||||
.field("id")
|
||||
.hint("base_visual_dev 里没有这条记录")
|
||||
.next("form.list", json!({}), "列出全部功能"));
|
||||
}
|
||||
|
||||
db.exec_params(
|
||||
"UPDATE base_visual_dev SET f_tables_data = $1 WHERE f_id = $2",
|
||||
&[&text, &visualdev_id.to_string()],
|
||||
)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 🔴 建表 + 回写的完整闭环。
|
||||
///
|
||||
/// 这是 MCP `schema.table.create` 工具背后的实现:
|
||||
/// 建表 → 回写 `f_tables_data` → 返回可用的模型。
|
||||
pub async fn create_and_sync(
|
||||
db: &Db,
|
||||
visualdev_id: &str,
|
||||
model: &ModelSchema,
|
||||
form: &FormSchema,
|
||||
dry_run: bool,
|
||||
) -> Result<CreateTablesOutcome, ToolError> {
|
||||
let outcome = create_tables(db, model, form, dry_run).await?;
|
||||
|
||||
if !dry_run {
|
||||
write_back_model(db, visualdev_id, &outcome.model).await?;
|
||||
}
|
||||
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// 🔴 一张表的 DDL 预览(只给主表,供 `schema.table.describe` 之类的诊断用)。
|
||||
pub fn preview_ddl(model: &ModelSchema, form: &FormSchema) -> Result<Vec<String>, ToolError> {
|
||||
let options = DdlOptions {
|
||||
logical_delete: form.logical_delete.unwrap_or(false),
|
||||
with_comments: false,
|
||||
primary_key_policy: form.primary_key_policy.unwrap_or(1),
|
||||
};
|
||||
let plan: CreatePlan = plan_create(model, &options).map_err(ddl_err)?;
|
||||
Ok(plan.render())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn model() -> ModelSchema {
|
||||
ModelSchema::from_str(
|
||||
r#"[{ "table": "t_main", "tableName": "主表", "typeId": "1", "fields": [
|
||||
{ "field": "F_Id", "dataType": "varchar", "dataLength": "50", "primaryKey": 1, "allowNull": 0 },
|
||||
{ "field": "F_Room", "dataType": "varchar", "dataLength": "100", "primaryKey": 0, "allowNull": 1 }
|
||||
]}]"#,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn form() -> FormSchema {
|
||||
FormSchema::from_str(
|
||||
r#"{ "formRef": "formRef", "formModel": "formData",
|
||||
"primaryKeyPolicy": 1, "logicalDelete": false, "fields": [] }"#,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// DDL 预览应产出 `CREATE TABLE`。
|
||||
#[test]
|
||||
fn preview_ddl_produces_create_table() {
|
||||
let ddl = preview_ddl(&model(), &form()).unwrap();
|
||||
assert_eq!(ddl.len(), 1);
|
||||
assert!(ddl[0].starts_with("CREATE TABLE t_main"), "{}", ddl[0]);
|
||||
assert!(ddl[0].contains("PRIMARY KEY (f_id, f_tenant_id)"), "{}", ddl[0]);
|
||||
}
|
||||
|
||||
/// 🔴 DDL 错误要转成有指导性的工具错误。
|
||||
#[test]
|
||||
fn ddl_error_becomes_actionable_tool_error() {
|
||||
let bad = ModelSchema::from_str(
|
||||
r#"[{ "table": "bad; DROP TABLE x", "typeId": "1", "fields": [
|
||||
{ "field": "F_Id", "dataType": "varchar", "primaryKey": 1 }
|
||||
]}]"#,
|
||||
)
|
||||
.unwrap();
|
||||
let err = preview_ddl(&bad, &form()).unwrap_err();
|
||||
assert_eq!(err.code, "ILLEGAL_IDENTIFIER");
|
||||
assert!(!err.hints.is_empty(), "非法标识符必须给出修复指引");
|
||||
}
|
||||
}
|
||||
pub use sspf_lowcode_exec::lowcode_ddl::*;
|
||||
@@ -1,503 +1,5 @@
|
||||
//! lowcode_seed —— **开发期**低代码示例数据种子(CLI `--seed-lowcode-demo`)。
|
||||
//!
|
||||
//! ## 它干什么
|
||||
//!
|
||||
//! 往库里灌**一份可用的低代码功能**,让 P2-b 的动态 CRUD 能被端到端验证:
|
||||
//!
|
||||
//! 1. `base_visual_dev` 一行(`f_form_data` = 官方 fixture 的控件树,
|
||||
//! `f_tables_data` = 官方 fixture 的表结构);
|
||||
//! 2. 按设计稿**真的建出物理表**(`test_receivable` / `test_details`);
|
||||
//! 3. 建表后**回写** `f_tables_data`(含平台追加的系统列)—— 与基线平台同款;
|
||||
//! 4. `base_visual_release` 一行(发布快照,三段 JSON 与 dev 一致)。
|
||||
//!
|
||||
//! ## 🔴 为什么要有这条通道
|
||||
//!
|
||||
//! P2-b 的动态 CRUD 需要「**一个真的低代码功能**」才能验证;而手点界面造一个
|
||||
//! 功能 = 慢且不可复现 ⇒ 提供一条**命令行、可重复**的通道:
|
||||
//!
|
||||
//! ```text
|
||||
//! ssw-platform --seed-lowcode-demo # 建表 + 灌功能定义
|
||||
//! ssw-platform --seed-lowcode-demo --dry-run # 只看要做什么,不碰库
|
||||
//! ```
|
||||
//!
|
||||
//! ## 🔴 数据来源是**官方初始化数据**
|
||||
//!
|
||||
//! fixture 与 `crates/sspf-lowcode/tests/fixtures/` 同源(基线平台初始化 SQL 里的
|
||||
//! 「应收费用」功能)⇒ 种出来的库**就是基线平台的低代码功能在 SSPF 里的样子**
|
||||
//! —— 验证才有意义(自己编的数据只能证明「自己和自己通」)。
|
||||
//!
|
||||
//! ## 🔴 只在开发档可用
|
||||
//!
|
||||
//! 它会**改真实库结构**(建表)⇒ 生产档直接拒绝(见 [`seed_gate`])。
|
||||
//!
|
||||
//! ## 🔴 幂等
|
||||
//!
|
||||
//! 固定 id + 「先查存在性再写」⇒ 重复跑不会撞复合主键,也不会留下重复行。
|
||||
//! lowcode_seed —— **转发壳**:真源在 [`sspf_lowcode_exec::lowcode_seed`](M5 低代码执行层下沉)。
|
||||
//! 🔴 只做转发、不含实现;CLI(`--seed-lowcode-demo`)与 MCP 适配器的调用路径不用改。
|
||||
//! 为什么留壳、闸门怎么改:见 `docs/CRATES-MIGRATION.md` §4 M5。
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use sspf_lowcode::{FormSchema, ModelSchema};
|
||||
use sspf_mcp::adapter::ToolError;
|
||||
|
||||
use crate::lowcode_crud::now_iso;
|
||||
use crate::lowcode_ddl;
|
||||
use crate::platform::config::Profile;
|
||||
use crate::platform::db::{pglite, Db};
|
||||
use crate::platform::registry::MAIN_SYSTEM_ID;
|
||||
|
||||
/// 示例功能在 `base_visual_dev` 里的**固定 id**。
|
||||
///
|
||||
/// 🔴 用**固定 id** 而不是新生成 UUID —— 固定 id 让种子幂等:
|
||||
/// 重复跑 `--seed-lowcode-demo` 是「更新同一条」而不是「插一堆重复的」。
|
||||
pub const DEMO_ID: &str = "lowcode-demo-receivable";
|
||||
|
||||
/// 示例功能的编码(`f_en_code`)—— AI 调 `data.record.insert` 时用它定位。
|
||||
///
|
||||
/// 🔴 与 MCP 工具文档里的示例(`crates/sspf-mcp/src/tools/lowcode.rs`)**逐字一致**
|
||||
/// ⇒ 文档里的示例直接可跑。
|
||||
pub const DEMO_EN_CODE: &str = "receivableDemo";
|
||||
|
||||
/// 示例功能的显示名。
|
||||
pub const DEMO_FULL_NAME: &str = "应收费用(低代码示例)";
|
||||
|
||||
/// 表单 fixture(相对项目根)。
|
||||
const FORM_FIXTURE: &str = "crates/sspf-lowcode/tests/fixtures/sample_form.json";
|
||||
|
||||
/// 模型 fixture(相对项目根)。
|
||||
const MODEL_FIXTURE: &str = "crates/sspf-lowcode/tests/fixtures/sample_model.json";
|
||||
|
||||
/// 单租户口径下的租户值(与 `lowcode_crud::DEFAULT_TENANT_ID` 同源)。
|
||||
const TENANT_ID: &str = "0";
|
||||
|
||||
/// 🔴 `base_visual_dev` / `base_visual_release` 的**共同列清单**与**类型**。
|
||||
///
|
||||
/// 官方两表逐列相同(`base_visual_release` 只多一列 `f_old_content`)
|
||||
/// ⇒ 用同一份清单写两张表 ⇒ 少一处漂移。
|
||||
///
|
||||
/// 🔴 每列带一个**列类型标记**(决定 SQL 里补哪层 cast):
|
||||
///
|
||||
/// | 标记 | 物理类型 | 参数 cast |
|
||||
/// |---|---|---|
|
||||
/// | `text` | `TEXT` / `VARCHAR` | `::text` |
|
||||
/// | `int` | `INTEGER` | `::text::integer` |
|
||||
/// | `bigint` | `BIGINT` | `::text::bigint` |
|
||||
/// | `ts` | `TIMESTAMP(0)` | `::text::timestamp` |
|
||||
///
|
||||
/// 🔴 **为什么参数统一按字符串送**:pglite 的扩展查询协议里,未标注类型的参数
|
||||
/// 会被服务端当成 `text`;本仓的整型/时间戳列需要显式再转一层。
|
||||
/// 列类型标记与清单**同序** ⇒ 少一处可能对不上的地方。
|
||||
const VISUAL_COLUMNS: &[(&str, &str)] = &[
|
||||
("f_id", "text"),
|
||||
("f_full_name", "text"),
|
||||
("f_en_code", "text"),
|
||||
("f_state", "int"),
|
||||
("f_type", "int"),
|
||||
("f_tables_data", "text"),
|
||||
("f_form_data", "text"),
|
||||
("f_column_data", "text"),
|
||||
("f_web_type", "int"),
|
||||
("f_app_column_data", "text"),
|
||||
("f_enable_flow", "int"),
|
||||
("f_description", "text"),
|
||||
("f_enabled_mark", "int"),
|
||||
("f_sort_code", "bigint"),
|
||||
("f_creator_time", "ts"),
|
||||
("f_creator_user_id", "text"),
|
||||
("f_last_modify_time", "ts"),
|
||||
("f_last_modify_user_id", "text"),
|
||||
("f_delete_mark", "int"),
|
||||
("f_tenant_id", "text"),
|
||||
("f_url_address", "text"),
|
||||
("f_web_address", "text"),
|
||||
("f_button_data", "text"),
|
||||
("f_system_id", "text"),
|
||||
];
|
||||
|
||||
/// 种子结果。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SeedOutcome {
|
||||
/// 功能 id(`base_visual_dev.f_id`)。
|
||||
pub form_id: String,
|
||||
/// 功能编码。
|
||||
pub en_code: String,
|
||||
/// 建出来的表(主表在前)。
|
||||
pub tables: Vec<String>,
|
||||
/// 已存在因而跳过的表。
|
||||
pub skipped: Vec<String>,
|
||||
/// 实际执行的 DDL。
|
||||
pub ddl: Vec<String>,
|
||||
/// 回写后的模型(`f_tables_data` 的新值)。
|
||||
pub model: Value,
|
||||
/// 诊断信息。
|
||||
pub notes: Vec<String>,
|
||||
/// 是否只是演练(没建表、没写库)。
|
||||
pub dry_run: bool,
|
||||
}
|
||||
|
||||
/// 🔴 **档位闸门**:只在开发档允许。
|
||||
///
|
||||
/// `SSW_PROFILE=prod`(或 `production`)⇒ 拒绝。
|
||||
///
|
||||
/// 理由:这条命令会**建表**(改真实库结构)并灌入示例数据 ——
|
||||
/// 生产库里既不该有示例表,也不该在启动期被一条命令改结构。
|
||||
///
|
||||
/// 纯函数 ⇒ 可单测(不依赖环境变量)。
|
||||
pub fn seed_gate(profile: Profile) -> Result<(), String> {
|
||||
match profile {
|
||||
Profile::Dev => Ok(()),
|
||||
Profile::Prod => Err(
|
||||
"--seed-lowcode-demo 只在开发档可用(SSW_PROFILE=prod/production)。\n\
|
||||
它会往库里**建表**并灌入示例数据 —— 生产库不该有这些。\n\
|
||||
确实要跑 ⇒ 把 SSW_PROFILE 改成 dev(或 unset),\
|
||||
并确认 PGLITE_DIR 指向的是开发库而不是生产库。"
|
||||
.to_string(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// fixture 的绝对路径(相对项目根)。
|
||||
pub fn fixture_path(project_dir: &Path, name: &str) -> PathBuf {
|
||||
project_dir.join(name)
|
||||
}
|
||||
|
||||
/// 🔴 读 fixture 文件。
|
||||
fn read_fixture(project_dir: &Path, rel: &str) -> Result<String, ToolError> {
|
||||
let path = fixture_path(project_dir, rel);
|
||||
std::fs::read_to_string(&path).map_err(|e| {
|
||||
ToolError::new(
|
||||
"FIXTURE_MISSING",
|
||||
format!("读不到官方 fixture:{}({e})", path.display()),
|
||||
)
|
||||
.field(rel)
|
||||
.hint("fixture 在 crates/sspf-lowcode/tests/fixtures/ 下,与基线平台初始化 SQL 同源")
|
||||
})
|
||||
}
|
||||
|
||||
/// 🔴 读官方 fixture,解析出(表单, 模型)。
|
||||
///
|
||||
/// 两个入口共用这一段 ⇒ 演练看到的与真跑执行的**一定是同一份设计稿**。
|
||||
fn load_demo_fixture(
|
||||
project_dir: &Path,
|
||||
) -> Result<(FormSchema, ModelSchema), ToolError> {
|
||||
let form_text = read_fixture(project_dir, FORM_FIXTURE)?;
|
||||
let model_text = read_fixture(project_dir, MODEL_FIXTURE)?;
|
||||
|
||||
let form = FormSchema::from_str(&form_text).map_err(|e| {
|
||||
ToolError::new(
|
||||
e.code(),
|
||||
format!("官方表单 fixture 解析失败: {}", e.message()),
|
||||
)
|
||||
.field(FORM_FIXTURE)
|
||||
})?;
|
||||
let model = ModelSchema::from_str(&model_text).map_err(|e| {
|
||||
ToolError::new(
|
||||
e.code(),
|
||||
format!("官方模型 fixture 解析失败: {}", e.message()),
|
||||
)
|
||||
.field(MODEL_FIXTURE)
|
||||
})?;
|
||||
|
||||
Ok((form, model))
|
||||
}
|
||||
|
||||
/// 🔴 **演练**:只看要建什么表,**不碰库**。
|
||||
///
|
||||
/// 🔴 **连数据库都不开** —— 演练的整个意义就是「什么都不发生」。
|
||||
/// 开库就意味着在数据目录里落一个临时 PG 实例(改磁盘状态)。
|
||||
pub fn preview_lowcode_demo(project_dir: &Path) -> Result<SeedOutcome, ToolError> {
|
||||
let (form, model) = load_demo_fixture(project_dir)?;
|
||||
let ddl = lowcode_ddl::preview_ddl(&model, &form)?;
|
||||
|
||||
let planned: Vec<String> = model
|
||||
.tables
|
||||
.iter()
|
||||
.map(|t| t.table.to_lowercase())
|
||||
.collect();
|
||||
|
||||
Ok(SeedOutcome {
|
||||
form_id: DEMO_ID.to_string(),
|
||||
en_code: DEMO_EN_CODE.to_string(),
|
||||
tables: planned,
|
||||
skipped: Vec::new(),
|
||||
ddl,
|
||||
model: model.raw.clone(),
|
||||
notes: vec!["dry-run:没有建表,也没有写库".to_string()],
|
||||
dry_run: true,
|
||||
})
|
||||
}
|
||||
|
||||
/// 🔴 低代码示例功能种子(**开发档专用**)。
|
||||
///
|
||||
/// ## 执行顺序(顺序不能换)
|
||||
///
|
||||
/// 1. 读官方 fixture(表单 + 模型);
|
||||
/// 2. 先写 `base_visual_dev`(**用原始模型**)—— 因为建表后的回写要求这行已存在;
|
||||
/// 3. `create_and_sync`:建表 + 回写 `f_tables_data`(含系统列);
|
||||
/// 4. 写 `base_visual_release`(**用回写后的模型**)—— 发布快照与 dev 一致。
|
||||
pub async fn seed_lowcode_demo(
|
||||
db: &Db,
|
||||
project_dir: &Path,
|
||||
) -> Result<SeedOutcome, ToolError> {
|
||||
let (form, model) = load_demo_fixture(project_dir)?;
|
||||
|
||||
// ---- DDL 预览(与真实执行用同一套生成规则)----
|
||||
let ddl = lowcode_ddl::preview_ddl(&model, &form)?;
|
||||
|
||||
// ---- 1. 先写 dev 行(原始模型)----
|
||||
upsert_visual_row(db, "base_visual_dev", DEMO_ID, &form.raw.to_string(), &model.raw.to_string())
|
||||
.await?;
|
||||
|
||||
// ---- 2. 建表 + 回写模型 ----
|
||||
let created = lowcode_ddl::create_and_sync(db, DEMO_ID, &model, &form, false).await?;
|
||||
|
||||
// ---- 3. 写 release 行(**回写后**的模型 ⇒ 与 dev 一致)----
|
||||
let rewritten_text = serde_json::to_string(&created.model).map_err(|e| {
|
||||
ToolError::new(
|
||||
"MODEL_SERIALIZE_FAILED",
|
||||
format!("回写后的模型序列化失败: {e}"),
|
||||
)
|
||||
})?;
|
||||
upsert_visual_row(
|
||||
db,
|
||||
"base_visual_release",
|
||||
DEMO_ID,
|
||||
&form.raw.to_string(),
|
||||
&rewritten_text,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let mut notes = created.notes.clone();
|
||||
notes.push(format!(
|
||||
"功能定义已写入 base_visual_dev 与 base_visual_release(id={DEMO_ID}, enCode={DEMO_EN_CODE})"
|
||||
));
|
||||
|
||||
Ok(SeedOutcome {
|
||||
form_id: DEMO_ID.to_string(),
|
||||
en_code: DEMO_EN_CODE.to_string(),
|
||||
tables: created.tables,
|
||||
skipped: created.skipped,
|
||||
ddl,
|
||||
model: created.model,
|
||||
notes,
|
||||
dry_run: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// 🔴 写(插入或更新)一行低代码功能定义。
|
||||
///
|
||||
/// ## 🔴 幂等策略
|
||||
///
|
||||
/// 「先查存在性,再决定 INSERT 还是 UPDATE」——
|
||||
/// `Db::exec_params` **不返回影响行数**(pglite 0.2.7 没这个能力),
|
||||
/// 所以不能用 `ON CONFLICT ... DO UPDATE`(那样也拿不到结果),
|
||||
/// 只能先 `SELECT` 判存在。
|
||||
async fn upsert_visual_row(
|
||||
db: &Db,
|
||||
table: &str,
|
||||
id: &str,
|
||||
form_data: &str,
|
||||
tables_data: &str,
|
||||
) -> Result<(), ToolError> {
|
||||
let exists = db
|
||||
.query_json_params(
|
||||
&format!("SELECT 1 AS \"x\" FROM {table} WHERE f_id = $1 LIMIT 1"),
|
||||
&[&id.to_string()],
|
||||
)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
|
||||
if exists.is_empty() {
|
||||
insert_visual_row(db, table, id, form_data, tables_data).await?;
|
||||
} else {
|
||||
update_visual_row(db, table, id, form_data, tables_data).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 🔴 一行的**字段值**(与 [`VISUAL_COLUMNS`] 同序)。
|
||||
fn visual_row_values(id: &str, form_data: &str, tables_data: &str) -> Vec<String> {
|
||||
let now = now_iso();
|
||||
let url = format!("lowcode/{DEMO_EN_CODE}/index");
|
||||
vec![
|
||||
id.to_string(),
|
||||
DEMO_FULL_NAME.to_string(),
|
||||
DEMO_EN_CODE.to_string(),
|
||||
"1".to_string(), // f_state:1 = 已发布
|
||||
"1".to_string(), // f_type:1 = 在线开发
|
||||
tables_data.to_string(),
|
||||
form_data.to_string(),
|
||||
"[]".to_string(), // f_column_data:列表列(空数组 = 不配列表页)
|
||||
"2".to_string(), // f_web_type:2 = PC 端
|
||||
"[]".to_string(), // f_app_column_data
|
||||
"0".to_string(), // f_enable_flow
|
||||
"开发期种子生成的低代码示例功能".to_string(),
|
||||
"1".to_string(), // f_enabled_mark
|
||||
"0".to_string(), // f_sort_code
|
||||
now.clone(), // f_creator_time
|
||||
"admin".to_string(),
|
||||
now.clone(), // f_last_modify_time
|
||||
"admin".to_string(),
|
||||
"0".to_string(), // f_delete_mark
|
||||
TENANT_ID.to_string(),
|
||||
url.clone(),
|
||||
url,
|
||||
"[]".to_string(), // f_button_data
|
||||
MAIN_SYSTEM_ID.to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
/// 🔴 插入一行低代码功能定义。
|
||||
async fn insert_visual_row(
|
||||
db: &Db,
|
||||
table: &str,
|
||||
id: &str,
|
||||
form_data: &str,
|
||||
tables_data: &str,
|
||||
) -> Result<(), ToolError> {
|
||||
let values = visual_row_values(id, form_data, tables_data);
|
||||
let cols: Vec<&str> = VISUAL_COLUMNS.iter().map(|(c, _)| *c).collect();
|
||||
let placeholders: Vec<String> = VISUAL_COLUMNS
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (_, ty))| format!("${}::{}", i + 1, cast_for(ty)))
|
||||
.collect();
|
||||
|
||||
let sql = format!(
|
||||
"INSERT INTO {table} ({}) VALUES ({})",
|
||||
cols.join(", "),
|
||||
placeholders.join(", ")
|
||||
);
|
||||
|
||||
let refs = build_params(&values);
|
||||
db.exec_params(&sql, &refs).await.map_err(db_err)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 🔴 更新一行低代码功能定义(只改「这个功能真的用到」的列)。
|
||||
async fn update_visual_row(
|
||||
db: &Db,
|
||||
table: &str,
|
||||
id: &str,
|
||||
form_data: &str,
|
||||
tables_data: &str,
|
||||
) -> Result<(), ToolError> {
|
||||
let values = visual_row_values(id, form_data, tables_data);
|
||||
let now = now_iso();
|
||||
|
||||
// 🔴 列清单里除 `f_id` 外全部更新(`f_creator_*` 保持首次种下的值)。
|
||||
// 参数编号要与 `set_cols` 的顺序严格对应 ⇒ 按 `VISUAL_COLUMNS` 里的下标取。
|
||||
let mut params: Vec<String> = Vec::new();
|
||||
let mut assignments: Vec<String> = Vec::new();
|
||||
for (i, (col, ty)) in VISUAL_COLUMNS.iter().enumerate() {
|
||||
if *col == "f_id" || *col == "f_creator_time" || *col == "f_creator_user_id" {
|
||||
continue;
|
||||
}
|
||||
// 🔴 `f_last_modify_time` 用**当前**时间(其余值原样回填)。
|
||||
let value = if *col == "f_last_modify_time" {
|
||||
now.clone()
|
||||
} else {
|
||||
values[i].clone()
|
||||
};
|
||||
params.push(value);
|
||||
assignments.push(format!("{col} = ${}::{}", params.len(), cast_for(ty)));
|
||||
}
|
||||
params.push(id.to_string());
|
||||
let id_pos = params.len();
|
||||
|
||||
let sql = format!(
|
||||
"UPDATE {table} SET {} WHERE f_id = ${id_pos}::text",
|
||||
assignments.join(", ")
|
||||
);
|
||||
|
||||
let refs = build_params(¶ms);
|
||||
db.exec_params(&sql, &refs).await.map_err(db_err)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 🔴 列类型标记 ⇒ SQL cast 片段。
|
||||
fn cast_for(kind: &str) -> &'static str {
|
||||
match kind {
|
||||
"int" => "text::integer",
|
||||
"bigint" => "text::bigint",
|
||||
"ts" => "text::timestamp",
|
||||
_ => "text",
|
||||
}
|
||||
}
|
||||
|
||||
/// 🔴 把参数向量转成可传给 `exec_params` 的引用数组。
|
||||
fn build_params(params: &[String]) -> Vec<&(dyn pglite::ToSql + Sync)> {
|
||||
params
|
||||
.iter()
|
||||
.map(|s| s as &(dyn pglite::ToSql + Sync))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 🔴 DB 错误转工具错误。
|
||||
fn db_err(e: pglite::Error) -> ToolError {
|
||||
ToolError::new("DB_ERROR", format!("数据库错误:{e}"))
|
||||
.hint("先确认数据库连接正常;这个错误通常来自 SQL 或连接配置")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// 🔴 **开发档放行**。
|
||||
#[test]
|
||||
fn dev_profile_is_allowed() {
|
||||
assert!(seed_gate(Profile::Dev).is_ok());
|
||||
}
|
||||
|
||||
/// 🔴 **生产档拒绝**(且要说得清为什么、怎么办)。
|
||||
#[test]
|
||||
fn prod_profile_is_rejected_with_guidance() {
|
||||
let err = seed_gate(Profile::Prod).unwrap_err();
|
||||
assert!(err.contains("SSW_PROFILE"), "报错要指明用哪个环境变量:{err}");
|
||||
assert!(err.contains("PGLITE_DIR"), "报错要提醒别指到生产库:{err}");
|
||||
}
|
||||
|
||||
/// 🔴 闸门**只认档位**,不读环境变量 ⇒ 纯函数、可单测。
|
||||
#[test]
|
||||
fn gate_depends_only_on_profile() {
|
||||
assert!(seed_gate(Profile::from_env_str("dev")).is_ok());
|
||||
assert!(seed_gate(Profile::from_env_str("")).is_ok());
|
||||
assert!(seed_gate(Profile::from_env_str("prod")).is_err());
|
||||
assert!(seed_gate(Profile::from_env_str("PRODUCTION")).is_err());
|
||||
}
|
||||
|
||||
/// 🔴 **列清单与字段值必须一一对应** —— 对不上会静默写错列。
|
||||
#[test]
|
||||
fn column_list_matches_value_count() {
|
||||
let values = visual_row_values("id", "form", "tables");
|
||||
assert_eq!(
|
||||
VISUAL_COLUMNS.len(),
|
||||
values.len(),
|
||||
"VISUAL_COLUMNS 的长度变了 ⇒ 同步改 visual_row_values"
|
||||
);
|
||||
}
|
||||
|
||||
/// 🔴 **列清单的 id 列必须是第一列** —— `UPDATE` 靠这个下标排除它。
|
||||
#[test]
|
||||
fn first_column_is_id() {
|
||||
assert_eq!(VISUAL_COLUMNS[0].0, "f_id");
|
||||
}
|
||||
|
||||
/// 🔴 cast 片段必须与列类型对得上(写错 ⇒ PG 类型错)。
|
||||
#[test]
|
||||
fn cast_for_matches_column_kinds() {
|
||||
assert_eq!(cast_for("text"), "text");
|
||||
assert_eq!(cast_for("int"), "text::integer");
|
||||
assert_eq!(cast_for("bigint"), "text::bigint");
|
||||
assert_eq!(cast_for("ts"), "text::timestamp");
|
||||
}
|
||||
|
||||
/// 🔴 fixture 路径拼在**项目根**下(不依赖 cwd)。
|
||||
#[test]
|
||||
fn fixture_path_is_under_project_root() {
|
||||
let p = fixture_path(Path::new("/tmp/proj"), FORM_FIXTURE);
|
||||
assert!(p.starts_with("/tmp/proj"), "{}", p.display());
|
||||
assert!(p.ends_with("sample_form.json"), "{}", p.display());
|
||||
}
|
||||
}
|
||||
pub use sspf_lowcode_exec::lowcode_seed::*;
|
||||
Reference in new issue
Block a user