把 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)
1241 lines
44 KiB
Rust
1241 lines
44 KiB
Rust
//! lowcode_crud —— 内核侧的**低代码动态 CRUD 执行层**(P2-b)。
|
||
//!
|
||
//! ## 分工
|
||
//!
|
||
//! | 层 | 位置 | 干什么 |
|
||
//! |---|---|---|
|
||
//! | 解析 / 校验 / **SQL 生成** | `sspf-lowcode`(纯计算,AR7) | 出 SQL 文本 + 参数 |
|
||
//! | **执行** | 本文件(内核) | 连库、跑 SQL、返回结果 |
|
||
//!
|
||
//! ⇒ SQL 生成的正确性由 `sspf-lowcode` 的单测覆盖;本文件只做「拿到 SQL 就执行」,
|
||
//! 没有分支逻辑 —— 这是刻意的分工。
|
||
//!
|
||
//! ## 🔴 四条执行层的硬约定
|
||
//!
|
||
//! 1. **主表先行、子表随后**:子表外键指向主表主键,顺序反了会插不进去。
|
||
//! 2. **一个事务**:主表失败 ⇒ 子表也不能留孤儿行。
|
||
//! pglite 有真事务 API(`transaction()` / `commit()` / `rollback()`)—— 用它。
|
||
//! 3. **写入前先比对真实库列**:设计稿自洽 ≠ 真实库有那列。
|
||
//! 官方数据里 `columnName` 全是 null,列名是从 `field` 推导的 ——
|
||
//! 推导必然有偏差(`F_CreatorTime` → `f_creatortime`,真实列可能是别的)。
|
||
//! ⇒ 落库前拿 `information_schema` 对一遍,**对不上就拒绝写**,
|
||
//! 并明确告诉 AI「设计稿与真实库不一致」。
|
||
//! 4. **子表更新走差集对账**:不是全量覆盖(详见 [`sspf_lowcode::diff_sub_rows`])。
|
||
//!
|
||
//! ## 🔴 为什么第 3 条不能省
|
||
//!
|
||
//! 省掉它 ⇒ 数据库报 `column "f_xxx" does not exist` ——
|
||
//! 这句话对 AI 毫无指导性(该改表单?改表?还是拼错了?)。
|
||
//! 自己做比对 ⇒ 报「设计稿声明了 f_xxx,但真实库没有这一列」,
|
||
//! 直接指到要改的地方。
|
||
//!
|
||
//! ## 🔴 值的类型:走 `::text` + 显式 cast
|
||
//!
|
||
//! pglite 绑参数时若不指定类型,PG 会把 `$1` **推断成目标列的类型**
|
||
//! (`timestamp` / `numeric` / `integer`),而我们绑的是 `Option<String>`
|
||
//! ⇒ 直接报 `cannot convert between the Rust type String and the Postgres type timestamp`。
|
||
//! ⇒ 一律 `$n::text`,再按列类型加 cast(`::numeric` / `::integer` / `::timestamp`)。
|
||
//!
|
||
//! ## 🔴 cast 靠 `param_columns`,不靠猜
|
||
//!
|
||
//! [`sspf_lowcode::Sql`] 自带「占位符 ↔ 列名」映射 ⇒ 执行层不需要
|
||
//! 「理解 SQL 是怎么拼的」,也不需要「按模型字段顺序猜第 n 个参数是哪一列」
|
||
//! (写入列顺序 ≠ 模型字段顺序 —— 系统列是运行时追加的,猜错就写脏数据)。
|
||
|
||
use std::collections::BTreeMap;
|
||
|
||
use pglite::ToSql;
|
||
use serde_json::{json, Value};
|
||
|
||
use sspf_lowcode::{
|
||
check_identifier, plan_delete, plan_insert, plan_update_full, sql::Sql, FieldNode, FormSchema,
|
||
ModelSchema, SqlError, SubUpdateContext, SubUpdateOptions, TableSchema, WriteContext,
|
||
};
|
||
use sspf_mcp::adapter::ToolError;
|
||
|
||
use sspf_core::db::Db;
|
||
use sspf_core::ids::new_uuid;
|
||
|
||
/// 🔴 **单租户**下的默认租户值。
|
||
///
|
||
/// ## 溯源
|
||
///
|
||
/// 基线平台 `GlobalConst`:
|
||
/// ```java
|
||
/// public static final String DEFAULT_TENANT_VALUE = "0";
|
||
/// ```
|
||
///
|
||
/// `TenantDataSourceUtil.getTenantColumn()`:
|
||
/// ```java
|
||
/// public static String getTenantColumn() {
|
||
/// String result = GlobalConst.DEFAULT_TENANT_VALUE;
|
||
/// if (isTenantColumn()) { // 只有「字段隔离」模式才取真实租户名
|
||
/// result = getTenantName();
|
||
/// }
|
||
/// return result;
|
||
/// }
|
||
/// ```
|
||
///
|
||
/// 本平台部署配置 `config.MultiTenancy: false` ⇒ `isTenantColumn()` 为 false
|
||
/// ⇒ **恒定返回 `"0"`**。
|
||
///
|
||
/// ## 🔴 为什么单租户下**仍然要写**租户列
|
||
///
|
||
/// `FlowFormDataUtil.addTenantId()` 是**无条件**执行的:
|
||
/// ```java
|
||
/// private void addTenantId(GeneralInsertDSL dsl, SqlTable t) {
|
||
/// dsl.set(t.column(TableFeildsEnum.TENANTID.getField()))
|
||
/// .toValue(TenantDataSourceUtil.getTenantColumn());
|
||
/// }
|
||
/// ```
|
||
/// ⇒ 单租户也会往 `f_tenant_id` 写 `"0"`。
|
||
/// 不写的话,列是 NOT NULL(`TableFeildsEnum.TENANTID` 的 nullSign = "NOT NULL")
|
||
/// ⇒ 插入直接失败。
|
||
pub const DEFAULT_TENANT_ID: &str = "0";
|
||
|
||
/// 动态 CRUD 的执行结果。
|
||
#[derive(Debug, Clone)]
|
||
pub struct CrudOutcome {
|
||
/// 主键 id。
|
||
pub id: String,
|
||
/// 实际执行的 SQL 条数(主表 + 子表)。
|
||
pub statements: usize,
|
||
/// 诊断信息(哪些列没写、为什么)。
|
||
pub notes: Vec<String>,
|
||
/// 计划好的 SQL(dry-run 时返回给调用方看)。
|
||
pub sql: Vec<Sql>,
|
||
/// 是否只是演练(没落库)。
|
||
pub dry_run: bool,
|
||
}
|
||
|
||
/// 把 lowcode 的错误转成结构化工具错误。
|
||
pub fn sql_err(e: SqlError) -> ToolError {
|
||
let mut t = ToolError::new(e.code(), e.message());
|
||
match &e {
|
||
SqlError::UnknownColumn { table, column } => {
|
||
t = t
|
||
.field(column)
|
||
.hint(format!(
|
||
"表 {table} 里没有列 {column};先 form.describe 看真实字段清单"
|
||
))
|
||
.next(
|
||
"form.describe",
|
||
json!({ "enCode": "<功能编码>" }),
|
||
"看这个功能的字段与列",
|
||
);
|
||
}
|
||
SqlError::MissingRequired { table, column, label } => {
|
||
t = t.field(column).hint(format!(
|
||
"必填字段「{label}」({table}.{column}) 必须给值;\
|
||
确实要留空就先把它从「必填」里去掉"
|
||
));
|
||
}
|
||
SqlError::UnknownTable(tbl) => {
|
||
t = t
|
||
.field("table")
|
||
.hint(format!("表 {tbl} 不在功能定义里 —— 表名白名单不通过"))
|
||
.next(
|
||
"form.validate",
|
||
json!({ "enCode": "<功能编码>" }),
|
||
"先体检这个功能",
|
||
);
|
||
}
|
||
SqlError::NoMainTable => {
|
||
t = t.hint("模型里没有 typeId=1 的主表 —— 这个功能定义可能不完整");
|
||
}
|
||
SqlError::NoPrimaryKey(tbl) => {
|
||
t = t.hint(format!(
|
||
"表 {tbl} 缺主键:入参没给,且调用方没生成 —— \
|
||
子表每行的主键需要调用方预先生成并登记"
|
||
));
|
||
}
|
||
SqlError::TypeMismatch { column, expected } => {
|
||
t = t.field(column).hint(format!("字段 {column} 应为 {expected}"));
|
||
}
|
||
SqlError::UnsupportedValue { column } => {
|
||
t = t.field(column).hint(format!(
|
||
"字段 {column} 的值是复杂对象 —— 只能给字符串/数字/数组;\
|
||
对象请先序列化成 JSON 字符串"
|
||
));
|
||
}
|
||
SqlError::IllegalIdentifier { kind, value } => {
|
||
t = t.hint(format!(
|
||
"{kind}「{value}」含非法字符,只能是字母/数字/下划线"
|
||
));
|
||
}
|
||
SqlError::NoColumnsToUpdate(tbl) => {
|
||
t = t.hint(format!(
|
||
"表 {tbl} 没有任何列要更新 —— 入参没给可写字段,或给的都是系统字段"
|
||
));
|
||
}
|
||
SqlError::MissingRelationValue { table, column } => {
|
||
t = t.hint(format!(
|
||
"子表 {table} 的外键指向主表的 {column},但这一列的值拿不到 —— \
|
||
它不是主键,需要先查出来再传进来"
|
||
));
|
||
}
|
||
SqlError::LogicalDeleteUnsupported(tbl) => {
|
||
t = t.hint(format!(
|
||
"表 {tbl} 没有删除标记列,不支持逻辑删除 —— \
|
||
这个功能要么该走物理删除,要么表建错了(logicalDelete 与建表不匹配)"
|
||
))
|
||
.next(
|
||
"form.validate",
|
||
json!({ "enCode": "<功能编码>" }),
|
||
"体检这个功能的逻辑删除设置",
|
||
);
|
||
}
|
||
}
|
||
t
|
||
}
|
||
|
||
/// 🔴 设计稿 vs 真实库:列名比对结果。
|
||
#[derive(Debug, Clone, PartialEq)]
|
||
pub struct ColumnMismatch {
|
||
/// 真实库里缺的设计稿列。
|
||
pub missing: Vec<String>,
|
||
/// 真实库有、但设计稿没声明的列(通常是系统列,不算错,仅供参考)。
|
||
pub extra: Vec<String>,
|
||
}
|
||
|
||
/// 取一张表在真实库里的列名。
|
||
pub async fn real_columns(db: &Db, table: &str) -> Result<Vec<String>, ToolError> {
|
||
let t = table.to_string();
|
||
let rows = db
|
||
.query_json_params(
|
||
"SELECT column_name AS \"name\" FROM information_schema.columns \
|
||
WHERE table_schema = 'public' AND table_name = $1 \
|
||
ORDER BY ordinal_position",
|
||
&[&t],
|
||
)
|
||
.await
|
||
.map_err(|e| {
|
||
ToolError::new("DB_ERROR", format!("读表结构失败: {e}"))
|
||
.hint("先 schema.table.list 确认表在不在")
|
||
.retryable()
|
||
})?;
|
||
Ok(rows
|
||
.into_iter()
|
||
.filter_map(|r| r["name"].as_str().map(str::to_string))
|
||
.collect())
|
||
}
|
||
|
||
/// 比对设计稿声明的列与真实库的列。
|
||
pub fn compare_columns(declared: &[String], actual: &[String]) -> ColumnMismatch {
|
||
let actual_lower: Vec<String> = actual.iter().map(|c| c.to_lowercase()).collect();
|
||
let missing: Vec<String> = declared
|
||
.iter()
|
||
.filter(|c| !actual_lower.contains(&c.to_lowercase()))
|
||
.cloned()
|
||
.collect();
|
||
let declared_lower: Vec<String> = declared.iter().map(|c| c.to_lowercase()).collect();
|
||
let extra: Vec<String> = actual
|
||
.iter()
|
||
.filter(|c| !declared_lower.contains(&c.to_lowercase()))
|
||
.cloned()
|
||
.collect();
|
||
ColumnMismatch { missing, extra }
|
||
}
|
||
|
||
/// 🔴 真实库里**根本没有这张表**时的错误。
|
||
pub fn table_missing_error(table: &str) -> ToolError {
|
||
ToolError::new("TABLE_NOT_IN_DB", format!("真实库里没有表 {table}")).field("table").hint(
|
||
"设计稿里的表还没建出来 —— 低代码功能要先「建表」再「存数据」。\
|
||
用 schema.table.list 看当前库有哪些表",
|
||
)
|
||
.next(
|
||
"schema.table.list",
|
||
json!({ "prefix": table }),
|
||
"看这张表在不在",
|
||
)
|
||
}
|
||
|
||
/// 构造写入上下文(把内核有的东西塞进去)。
|
||
pub fn build_context(
|
||
user_id: Option<&str>,
|
||
tenant_id: Option<&str>,
|
||
now: Option<&str>,
|
||
) -> WriteContext {
|
||
WriteContext {
|
||
user_id: user_id.map(str::to_string),
|
||
organize_ids: Vec::new(),
|
||
position_ids: Vec::new(),
|
||
tenant_id: tenant_id.map(str::to_string),
|
||
bill_numbers: Default::default(),
|
||
primary_keys: Default::default(),
|
||
now: now.map(str::to_string),
|
||
relation_values: Default::default(),
|
||
}
|
||
}
|
||
|
||
/// 🔴 当前时间(ISO8601,秒精度)。
|
||
///
|
||
/// 🔴 为什么用**秒精度**而不是毫秒/纳秒:
|
||
/// 低代码表的 `f_creatortime` / `f_lastmodifytime` 在官方 DDL 里是
|
||
/// `timestamp`(**没有时区**)⇒ 传 ISO 带 `T` 和 `Z` 的串会被 PG
|
||
/// 解析成 `timestamptz` 再转 `timestamp` ⇒ **会随时区偏移几个小时**。
|
||
/// 统一给 `YYYY-MM-DD HH:MM:SS` 最稳(PG 直接当 timestamp 字面量)。
|
||
pub fn now_iso() -> String {
|
||
chrono::Local::now()
|
||
.format("%Y-%m-%d %H:%M:%S")
|
||
.to_string()
|
||
}
|
||
|
||
/// 执行一次**新增**(主表 + 子表),全部落在一个事务里。
|
||
///
|
||
/// `dry_run = true` ⇒ 只生成 SQL + 校验列,**不落库**。
|
||
pub async fn insert_record(
|
||
db: &Db,
|
||
form: &FormSchema,
|
||
model: &ModelSchema,
|
||
payload: &Value,
|
||
ctx: &mut WriteContext,
|
||
dry_run: bool,
|
||
) -> Result<CrudOutcome, ToolError> {
|
||
let main_table = model.main_table().ok_or_else(|| {
|
||
ToolError::new("NO_MAIN_TABLE", "模型里没有主表(typeId=1)")
|
||
.hint("这个功能定义不完整")
|
||
})?;
|
||
let main_name = main_table.table.clone();
|
||
|
||
// 🔴 落库前先确认表在真实库里
|
||
let real = real_columns(db, &main_name).await?;
|
||
if real.is_empty() {
|
||
return Err(table_missing_error(&main_name));
|
||
}
|
||
|
||
// 生成主键
|
||
let main_id = new_uuid();
|
||
ctx.set_primary_key(main_name.clone(), main_id.clone());
|
||
|
||
// 子表每行也要主键(Java 侧服务端现生成 UUID)
|
||
for sub in form.sub_tables() {
|
||
let Some(sub_model) = resolve_sub_model(model, sub) else {
|
||
continue;
|
||
};
|
||
let rows = sub_rows(payload, &sub.v_model, &sub_model.table);
|
||
let Some(arr) = rows.as_ref().and_then(|v| v.as_array()) else {
|
||
continue;
|
||
};
|
||
for i in 0..arr.len() {
|
||
let key = new_uuid();
|
||
ctx.set_sub_row_key(&sub_model.table, &main_id, i, key);
|
||
}
|
||
}
|
||
|
||
let plan = plan_insert(form, model, payload, ctx, &main_id).map_err(sql_err)?;
|
||
|
||
// 🔴 逐条比对真实库列 —— 对不上就**拒绝写**,而不是让数据库报错
|
||
let mut notes: Vec<String> = Vec::new();
|
||
let mut real_cols: Vec<(String, Vec<String>)> = Vec::new();
|
||
for stmt in plan.all() {
|
||
let cols = columns_of_sql(&stmt.text);
|
||
let actual = match real_cols.iter().find(|(t, _)| t == &stmt.table) {
|
||
Some((_, c)) => c.clone(),
|
||
None => {
|
||
let a = real_columns(db, &stmt.table).await?;
|
||
if a.is_empty() {
|
||
return Err(table_missing_error(&stmt.table));
|
||
}
|
||
real_cols.push((stmt.table.clone(), a.clone()));
|
||
a
|
||
}
|
||
};
|
||
let diff = compare_columns(&cols, &actual);
|
||
if !diff.missing.is_empty() {
|
||
return Err(column_mismatch_error(&stmt.table, &diff, &actual));
|
||
}
|
||
if !diff.extra.is_empty() {
|
||
notes.push(format!(
|
||
"表 {} 真实库里还有设计稿没声明的列(未写入):{}",
|
||
stmt.table,
|
||
diff.extra.join(", ")
|
||
));
|
||
}
|
||
}
|
||
|
||
let stmts: Vec<Sql> = plan.all().into_iter().cloned().collect();
|
||
|
||
// 🔴 **业务校验**(唯一性 / 业务主键)—— 必须在真正写库**之前**做。
|
||
//
|
||
// 基线平台 `VisualdevModelDataServiceImpl.visualCreate()`:
|
||
// ```java
|
||
// String b = formCheckUtils.checkForm(checkFormModel);
|
||
// if (StringUtil.isNotEmpty(b)) { throw new WorkFlowException(b); }
|
||
// flowFormDataUtil.create(dataModel);
|
||
// ```
|
||
// ⇒ 校验失败 ⇒ **一条 SQL 都不执行**。
|
||
//
|
||
// dry-run 也要做校验:dry-run 的意义是「先看会不会被拦」。
|
||
// 校验不过还返回 SQL,AI 会误以为「只差一步就能落库」。
|
||
//
|
||
// 新增场景 `record_id = None` ⇒ 不排除任何行。
|
||
crate::lowcode_check::check_unique_fields(db, form, model, payload, None).await?;
|
||
crate::lowcode_check::check_business_key(db, form, model, payload, None).await?;
|
||
|
||
if dry_run {
|
||
return Ok(CrudOutcome {
|
||
id: main_id,
|
||
statements: stmts.len(),
|
||
notes,
|
||
sql: stmts,
|
||
dry_run: true,
|
||
});
|
||
}
|
||
|
||
let count = execute_plan(db, model, &stmts).await?;
|
||
|
||
Ok(CrudOutcome {
|
||
id: main_id,
|
||
statements: count,
|
||
notes,
|
||
sql: stmts,
|
||
dry_run: false,
|
||
})
|
||
}
|
||
|
||
/// 🔴 记录不存在的错误(AI 据此自纠:先查再改)。
|
||
pub fn record_missing_error(table: &str, record_id: &str) -> ToolError {
|
||
ToolError::new(
|
||
"RECORD_NOT_FOUND",
|
||
format!("表 {table} 里没有 id 为 {record_id} 的记录"),
|
||
)
|
||
.field("recordId")
|
||
.hint("记录可能已被删除;先用 data.query 查一遍确认 id")
|
||
.next(
|
||
"data.query",
|
||
json!({ "enCode": "<功能编码>" }),
|
||
"查这条记录还在不在",
|
||
)
|
||
}
|
||
|
||
/// 执行一次**更新**(主表 + 子表差集对账)。
|
||
///
|
||
/// ## 🔴 `only_update` 的口径(对齐基线平台)
|
||
///
|
||
/// 基线平台 `DataModel.onlyUpdate`:
|
||
/// ```java
|
||
/// // 子表仅修改
|
||
/// private Boolean onlyUpdate = false;
|
||
/// ```
|
||
/// ```java
|
||
/// if (CollUtil.isNotEmpty(deleteList) && !onlyUpdate) { /* 删缺失的旧行 */ }
|
||
/// ```
|
||
///
|
||
/// ⇒ `onlyUpdate = true` ⇒ **不删**入参里缺失的旧行(只更新/新增)。
|
||
///
|
||
/// 🔴 **基线的正常 HTTP 路径恒为 false**:
|
||
/// `VisualdevModelDataController` 构造 `VisualParamModel` 时**没有**设 `onlyUpdate`
|
||
/// ⇒ 只有 Excel 导入(`OnlineExcelUtil`)与流程场景才可能为 true。
|
||
/// ⇒ 本函数默认 `false`,MCP 层**不暴露**这个开关(暴露了会让 AI 以为
|
||
/// 「默认只更新不删除」,与基线的实际行为相反)。
|
||
#[allow(clippy::too_many_arguments)]
|
||
pub async fn update_record(
|
||
db: &Db,
|
||
form: &FormSchema,
|
||
model: &ModelSchema,
|
||
payload: &Value,
|
||
ctx: &mut WriteContext,
|
||
record_id: &str,
|
||
dry_run: bool,
|
||
) -> Result<CrudOutcome, ToolError> {
|
||
update_record_with(db, form, model, payload, ctx, record_id, dry_run, false).await
|
||
}
|
||
|
||
/// 带 `only_update` 的更新(默认路径走 [`update_record`])。
|
||
#[allow(clippy::too_many_arguments)]
|
||
pub async fn update_record_with(
|
||
db: &Db,
|
||
form: &FormSchema,
|
||
model: &ModelSchema,
|
||
payload: &Value,
|
||
ctx: &mut WriteContext,
|
||
record_id: &str,
|
||
dry_run: bool,
|
||
only_update: bool,
|
||
) -> Result<CrudOutcome, ToolError> {
|
||
let main_table = model.main_table().ok_or_else(|| {
|
||
ToolError::new("NO_MAIN_TABLE", "模型里没有主表(typeId=1)")
|
||
})?;
|
||
let main_name = main_table.table.clone();
|
||
|
||
let real = real_columns(db, &main_name).await?;
|
||
if real.is_empty() {
|
||
return Err(table_missing_error(&main_name));
|
||
}
|
||
|
||
// 🔴 **先确认记录存在** —— 否则错误会一路飘到子表查询上,
|
||
// 变成一句毫无指导性的 `DB_ERROR`(AI 不知道是「记录没了」还是「库坏了」)。
|
||
ensure_record_exists(db, model, record_id).await?;
|
||
|
||
// 🔴 **顺序很重要**:先查主表那一行的**关联列实际值**,再收集子表上下文。
|
||
//
|
||
// 子表外键的值 = 主表 `relationField` 指向的那一列的值
|
||
// (基线平台:`mainMap.get(table.getRelationField())`)。
|
||
// 当 `relationField` 就是主键时,值 = 主键,收集子表上下文时回落到 `record_id` 没问题;
|
||
// 但当它指向**别的列**(如业务编码 `F_Code`)时,
|
||
// 不先查库就拿不到值 ⇒ 外键会退化成主键 ⇒ 子表挂错父行。
|
||
//
|
||
// 之前顺序反了(先 collect 再 fetch)⇒ 非主键 relationField 场景下
|
||
// `collect_sub_contexts` 拿不到关联值,回落成 `main_id`。
|
||
let relation_values = fetch_relation_values(db, form, model, record_id).await?;
|
||
for (col, val) in &relation_values {
|
||
ctx.set_relation_value(col, val.clone());
|
||
}
|
||
|
||
// 🔴 子表差集需要「旧行主键」—— 查库在**事务外**做(避免持锁期间再开事务死锁)。
|
||
let logical = form.logical_delete.unwrap_or(false);
|
||
let sub_ctxs = collect_sub_contexts(db, form, model, ctx, record_id, logical, only_update).await?;
|
||
|
||
let plan = plan_update_full(form, model, payload, ctx, record_id, &sub_ctxs).map_err(sql_err)?;
|
||
|
||
let mut notes: Vec<String> = Vec::new();
|
||
let mut real_cols: Vec<(String, Vec<String>)> = Vec::new();
|
||
for stmt in plan.all() {
|
||
let cols = columns_of_sql(&stmt.text);
|
||
if cols.is_empty() {
|
||
continue;
|
||
}
|
||
let actual = match real_cols.iter().find(|(t, _)| t == &stmt.table) {
|
||
Some((_, c)) => c.clone(),
|
||
None => {
|
||
let a = real_columns(db, &stmt.table).await?;
|
||
if a.is_empty() {
|
||
return Err(table_missing_error(&stmt.table));
|
||
}
|
||
real_cols.push((stmt.table.clone(), a.clone()));
|
||
a
|
||
}
|
||
};
|
||
let diff = compare_columns(&cols, &actual);
|
||
if !diff.missing.is_empty() {
|
||
return Err(column_mismatch_error(&stmt.table, &diff, &actual));
|
||
}
|
||
if !diff.extra.is_empty() {
|
||
notes.push(format!(
|
||
"表 {} 真实库里还有设计稿没声明的列(未写入):{}",
|
||
stmt.table,
|
||
diff.extra.join(", ")
|
||
));
|
||
}
|
||
}
|
||
|
||
let stmts: Vec<Sql> = plan.all().into_iter().cloned().collect();
|
||
|
||
// 🔴 **业务校验**(唯一性 / 业务主键)—— 更新场景要**排除自己那行**。
|
||
//
|
||
// 基线平台 `FormCheckUtils` 的唯一性 SQL:
|
||
// ```java
|
||
// if (StringUtils.isNotEmpty(id)) {
|
||
// where.and(sqlTable.column(mainKeyModel.getField()), SqlBuilder.isNotEqualTo(realId));
|
||
// }
|
||
// ```
|
||
// ⇒ 不排除自己 ⇒ 改一下别的字段也会被判「重复」。
|
||
crate::lowcode_check::check_unique_fields(db, form, model, payload, Some(record_id)).await?;
|
||
crate::lowcode_check::check_business_key(db, form, model, payload, Some(record_id)).await?;
|
||
|
||
if dry_run {
|
||
return Ok(CrudOutcome {
|
||
id: record_id.to_string(),
|
||
statements: stmts.len(),
|
||
notes,
|
||
sql: stmts,
|
||
dry_run: true,
|
||
});
|
||
}
|
||
|
||
let count = execute_plan(db, model, &stmts).await?;
|
||
|
||
Ok(CrudOutcome {
|
||
id: record_id.to_string(),
|
||
statements: count,
|
||
notes,
|
||
sql: stmts,
|
||
dry_run: false,
|
||
})
|
||
}
|
||
|
||
/// 执行一次**删除**(逻辑 / 物理按 `form.logicalDelete`)。
|
||
pub async fn delete_record(
|
||
db: &Db,
|
||
form: &FormSchema,
|
||
model: &ModelSchema,
|
||
ctx: &mut WriteContext,
|
||
record_id: &str,
|
||
dry_run: bool,
|
||
) -> Result<CrudOutcome, ToolError> {
|
||
let main_table = model.main_table().ok_or_else(|| {
|
||
ToolError::new("NO_MAIN_TABLE", "模型里没有主表(typeId=1)")
|
||
})?;
|
||
let main_name = main_table.table.clone();
|
||
|
||
let real = real_columns(db, &main_name).await?;
|
||
if real.is_empty() {
|
||
return Err(table_missing_error(&main_name));
|
||
}
|
||
|
||
// 🔴 先确认记录存在(否则错误会飘到子表查询上,变成没指导性的 DB_ERROR)。
|
||
ensure_record_exists(db, model, record_id).await?;
|
||
|
||
let logical = form.logical_delete.unwrap_or(false);
|
||
|
||
// 🔴 子表外键的值可能不是主键(`relationField` 指向别的列)⇒ 先查主表那一行。
|
||
let relation_values = fetch_relation_values(db, form, model, record_id).await?;
|
||
for (col, val) in &relation_values {
|
||
ctx.set_relation_value(col, val.clone());
|
||
}
|
||
|
||
// 逻辑删除但表里没有删除列 ⇒ `plan_delete` 会报 `LOGICAL_DELETE_UNSUPPORTED`。
|
||
// 那种情况**不退化成物理删**(用户以为逻辑删了,实际物理删 ⇒ 审计链断)。
|
||
let plan = plan_delete(form, model, ctx, record_id).map_err(sql_err)?;
|
||
|
||
let mut notes: Vec<String> = Vec::new();
|
||
let mut real_cols: Vec<(String, Vec<String>)> = Vec::new();
|
||
for stmt in plan.all() {
|
||
let cols = columns_of_sql(&stmt.text);
|
||
if cols.is_empty() {
|
||
continue;
|
||
}
|
||
let actual = match real_cols.iter().find(|(t, _)| t == &stmt.table) {
|
||
Some((_, c)) => c.clone(),
|
||
None => {
|
||
let a = real_columns(db, &stmt.table).await?;
|
||
if a.is_empty() {
|
||
return Err(table_missing_error(&stmt.table));
|
||
}
|
||
real_cols.push((stmt.table.clone(), a.clone()));
|
||
a
|
||
}
|
||
};
|
||
let diff = compare_columns(&cols, &actual);
|
||
if !diff.missing.is_empty() {
|
||
return Err(column_mismatch_error(&stmt.table, &diff, &actual));
|
||
}
|
||
if !diff.extra.is_empty() {
|
||
notes.push(format!(
|
||
"表 {} 真实库里还有设计稿没声明的列(未写入):{}",
|
||
stmt.table,
|
||
diff.extra.join(", ")
|
||
));
|
||
}
|
||
}
|
||
|
||
notes.push(if logical {
|
||
"逻辑删除:置删除标记,数据仍在表里".to_string()
|
||
} else {
|
||
"物理删除:行会真从表里消失(logicalDelete=false)".to_string()
|
||
});
|
||
|
||
let stmts: Vec<Sql> = plan.all().into_iter().cloned().collect();
|
||
|
||
if dry_run {
|
||
return Ok(CrudOutcome {
|
||
id: record_id.to_string(),
|
||
statements: stmts.len(),
|
||
notes,
|
||
sql: stmts,
|
||
dry_run: true,
|
||
});
|
||
}
|
||
|
||
let count = execute_plan(db, model, &stmts).await?;
|
||
|
||
Ok(CrudOutcome {
|
||
id: record_id.to_string(),
|
||
statements: count,
|
||
notes,
|
||
sql: stmts,
|
||
dry_run: false,
|
||
})
|
||
}
|
||
|
||
/// 🔴 确认主记录存在(更新 / 删除前必查)。
|
||
///
|
||
/// ## 为什么必须单独查一次
|
||
///
|
||
/// 更新流程后面会去查子表旧行、关联列值 —— 那些查询用的都是 `record_id`。
|
||
/// 记录不存在时,错误会飘到子表查询上,变成一句
|
||
/// `DB_ERROR: 查子表旧行失败: relation "xxx" does not exist` ——
|
||
/// AI 看到完全不知道是「记录没了」还是「库坏了」。
|
||
///
|
||
/// ⇒ 先明确报 `RECORD_NOT_FOUND`,并提示「先用 data.query 查一遍」。
|
||
///
|
||
/// ## 🔴 主键列**从模型推导**,不写死 `f_id`
|
||
///
|
||
/// Java `getKey()`:取模型里 `primaryKey=1` 且**不是租户列**的那一列。
|
||
/// 官方模型里 `f_tenant_id` 也是 `primaryKey=1` ⇒ 必须排除。
|
||
async fn ensure_record_exists(
|
||
db: &Db,
|
||
model: &ModelSchema,
|
||
record_id: &str,
|
||
) -> Result<(), ToolError> {
|
||
let Some(main_table) = model.main_table() else {
|
||
return Ok(());
|
||
};
|
||
let table = main_table.table.clone();
|
||
let pk_col = main_table
|
||
.primary_keys()
|
||
.into_iter()
|
||
.find(|c| !c.contains("f_tenant_id"))
|
||
.unwrap_or_else(|| "f_id".to_string());
|
||
|
||
// 🔴 表名/列名来自用户可编辑的模型 JSON ⇒ 进 SQL 前过标识符检查。
|
||
check_identifier("表名", &table).map_err(sql_err)?;
|
||
check_identifier("列名", &pk_col).map_err(sql_err)?;
|
||
|
||
let id = record_id.to_string();
|
||
let sql = format!("SELECT {pk_col} AS \"id\" FROM {table} WHERE {pk_col} = $1 LIMIT 1");
|
||
let rows = db
|
||
.query_json_params(&sql, &[&id])
|
||
.await
|
||
.map_err(|e| ToolError::new("DB_ERROR", format!("查记录失败: {e}")).retryable())?;
|
||
if rows.is_empty() {
|
||
return Err(record_missing_error(&table, record_id));
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// 🔴 收集子表更新的上下文(**旧行主键**从库里查)。
|
||
///
|
||
/// 差集对账的前提是知道「旧库里有哪些行」。
|
||
/// 本函数是**纯查库**(不改数据)⇒ 放在事务外执行,避免持锁期间再开事务。
|
||
async fn collect_sub_contexts(
|
||
db: &Db,
|
||
form: &FormSchema,
|
||
model: &ModelSchema,
|
||
ctx: &WriteContext,
|
||
main_id: &str,
|
||
logical: bool,
|
||
only_update: bool,
|
||
) -> Result<BTreeMap<String, SubUpdateContext>, ToolError> {
|
||
let mut out: BTreeMap<String, SubUpdateContext> = BTreeMap::new();
|
||
|
||
for sub in form.sub_tables() {
|
||
let Some(sub_model) = resolve_sub_model(model, sub) else {
|
||
continue;
|
||
};
|
||
let Some(fk_col) = sub_model.foreign_key_column() else {
|
||
return Err(sql_err(SqlError::UnknownColumn {
|
||
table: sub_model.table.clone(),
|
||
column: "tableField".to_string(),
|
||
}));
|
||
};
|
||
let sub_pk = sub_model
|
||
.primary_keys()
|
||
.into_iter()
|
||
.find(|c| !c.contains("f_tenant_id"))
|
||
.unwrap_or_else(|| "f_id".to_string());
|
||
|
||
// 🔴 表名/列名进 SQL 之前必须过标识符检查。
|
||
//
|
||
// 这些名字来自**用户可编辑的模型 JSON**(`f_tables_data`)。
|
||
// 参数化只能防「值注入」,**防不住结构注入** ——
|
||
// 表名/列名是拼进 SQL 文本的,不是占位符。
|
||
// ⇒ 规则与生成层共用同一份(`sspf_lowcode::check_identifier`),
|
||
// 避免「生成层拦了、执行层漏了」的漏洞。
|
||
for (kind, name) in [
|
||
("表名", sub_model.table.as_str()),
|
||
("列名", fk_col.as_str()),
|
||
("列名", sub_pk.as_str()),
|
||
] {
|
||
check_identifier(kind, name).map_err(sql_err)?;
|
||
}
|
||
|
||
// 外键的值:主表 `relationField` 指向的那一列的实际值。
|
||
let fk_value = ctx
|
||
.relation_value(sub_model)
|
||
.unwrap_or_else(|| main_id.to_string());
|
||
|
||
// 查旧行主键
|
||
let sql = format!(
|
||
"SELECT {sub_pk} AS \"k\" FROM {table} WHERE {fk_col} = $1",
|
||
sub_pk = sub_pk,
|
||
table = sub_model.table,
|
||
fk_col = fk_col,
|
||
);
|
||
let rows = db
|
||
.query_json_params(&sql, &[&fk_value])
|
||
.await
|
||
.map_err(|e| {
|
||
ToolError::new("DB_ERROR", format!("查子表旧行失败: {e}"))
|
||
.hint("子表可能还没建出来")
|
||
.retryable()
|
||
})?;
|
||
let old_keys: Vec<String> = rows
|
||
.into_iter()
|
||
.filter_map(|r| r["k"].as_str().map(str::to_string))
|
||
.collect();
|
||
|
||
let mut sub_ctx = SubUpdateContext::new(
|
||
old_keys,
|
||
fk_col.clone(),
|
||
fk_value,
|
||
SubUpdateOptions {
|
||
only_update,
|
||
logical_delete: logical,
|
||
},
|
||
);
|
||
// 🔴 子表行主键由内核生成(Java 侧是 `RandomUtil.uuId()`)。
|
||
sub_ctx.row_key_generator = Some(|_| new_uuid());
|
||
out.insert(sub_model.table.clone(), sub_ctx);
|
||
}
|
||
|
||
Ok(out)
|
||
}
|
||
|
||
/// 🔴 查主表那一行的**关联列**实际值(子表外键要指向它)。
|
||
///
|
||
/// 基线平台:`Object relationFieldValue = mainMap.get(table.getRelationField());`
|
||
/// —— 读的是**主表那一行的实际值**,不是主键。
|
||
///
|
||
/// `relationField` 通常就是主键列 ⇒ 这次查询走的是「白名单内的表名 + 白名单内的列名」。
|
||
async fn fetch_relation_values(
|
||
db: &Db,
|
||
form: &FormSchema,
|
||
model: &ModelSchema,
|
||
main_id: &str,
|
||
) -> Result<Vec<(String, String)>, ToolError> {
|
||
let Some(main_table) = model.main_table() else {
|
||
return Ok(Vec::new());
|
||
};
|
||
let main_pk = main_table
|
||
.primary_keys()
|
||
.into_iter()
|
||
.find(|c| !c.contains("f_tenant_id"))
|
||
.unwrap_or_else(|| "f_id".to_string());
|
||
|
||
// 🔴 表名/主键列名进 SQL 之前必须过标识符检查(同 [`collect_sub_contexts`])。
|
||
check_identifier("表名", &main_table.table).map_err(sql_err)?;
|
||
check_identifier("列名", &main_pk).map_err(sql_err)?;
|
||
|
||
// 收集所有子表用到的关联列
|
||
let mut cols: Vec<String> = Vec::new();
|
||
for sub in form.sub_tables() {
|
||
let Some(sub_model) = resolve_sub_model(model, sub) else {
|
||
continue;
|
||
};
|
||
if let Some(rel) = sub_model.relation_column() {
|
||
// 🔴 关联列名同样来自用户可编辑的模型 JSON ⇒ 也要过检查。
|
||
check_identifier("列名", &rel).map_err(sql_err)?;
|
||
if !cols.contains(&rel) {
|
||
cols.push(rel);
|
||
}
|
||
}
|
||
}
|
||
if cols.is_empty() {
|
||
return Ok(Vec::new());
|
||
}
|
||
|
||
// 一次查出来
|
||
let sel: Vec<String> = cols.iter().map(|c| format!("{c} AS \"{c}\"")).collect();
|
||
let sql = format!(
|
||
"SELECT {} FROM {} WHERE {} = $1",
|
||
sel.join(", "),
|
||
main_table.table,
|
||
main_pk
|
||
);
|
||
let rows = db
|
||
.query_json_params(&sql, &[&main_id.to_string()])
|
||
.await
|
||
.map_err(|e| {
|
||
ToolError::new("DB_ERROR", format!("查主表关联列失败: {e}")).retryable()
|
||
})?;
|
||
|
||
let Some(row) = rows.first() else {
|
||
return Ok(Vec::new());
|
||
};
|
||
|
||
let mut out = Vec::new();
|
||
for c in cols {
|
||
if let Some(v) = row.get(&c) {
|
||
let text = match v {
|
||
Value::String(s) => s.clone(),
|
||
Value::Null => continue,
|
||
other => other.to_string(),
|
||
};
|
||
out.push((c, text));
|
||
}
|
||
}
|
||
Ok(out)
|
||
}
|
||
|
||
/// 🔴 在一个事务里执行整组 SQL。
|
||
///
|
||
/// pglite 的 `transaction()` 会拿**独占锁**(`lock_for_transaction`),
|
||
/// 所以事务期间不会有别的请求插进来 —— 不会出现「A 写了主表、B 改了子表」的交错。
|
||
async fn execute_plan(
|
||
db: &Db,
|
||
model: &ModelSchema,
|
||
stmts: &[Sql],
|
||
) -> Result<usize, ToolError> {
|
||
if stmts.is_empty() {
|
||
return Ok(0);
|
||
}
|
||
let tx = db.begin().await.map_err(|e| {
|
||
ToolError::new("DB_ERROR", format!("开事务失败: {e}")).retryable()
|
||
})?;
|
||
|
||
for stmt in stmts {
|
||
let table = model.table(&stmt.table);
|
||
let sql_text = render_with_casts(&stmt.text, &stmt.params, &stmt.param_columns, table);
|
||
let params = params_as_text(&stmt.params);
|
||
let refs: Vec<&(dyn ToSql + Sync)> =
|
||
params.iter().map(|v| v as &(dyn ToSql + Sync)).collect();
|
||
|
||
if let Err(e) = tx.exec_params(&sql_text, &refs).await {
|
||
let _ = tx.rollback().await;
|
||
return Err(ToolError::new("DB_ERROR", format!("写库失败: {e}"))
|
||
.hint("多半是列名与真实表对不上;先 form.validate 再看真实表的列")
|
||
.retryable());
|
||
}
|
||
}
|
||
|
||
tx.commit().await.map_err(|e| {
|
||
ToolError::new("DB_ERROR", format!("提交事务失败: {e}")).retryable()
|
||
})?;
|
||
|
||
Ok(stmts.len())
|
||
}
|
||
|
||
/// 🔴 列不一致时的结构化错误。
|
||
fn column_mismatch_error(
|
||
table: &str,
|
||
diff: &ColumnMismatch,
|
||
actual: &[String],
|
||
) -> ToolError {
|
||
ToolError::new(
|
||
"COLUMN_MISMATCH",
|
||
format!(
|
||
"表 {} 缺少设计稿声明的列:{}",
|
||
table,
|
||
diff.missing.join(", ")
|
||
),
|
||
)
|
||
.field(diff.missing.first().map(|s| s.as_str()).unwrap_or(""))
|
||
.hint(format!(
|
||
"真实库里 {} 只有这些列:{}。\
|
||
设计稿的列名是从 `field` 推导的(官方数据 columnName 全是 null),\
|
||
推导必然有偏差 —— 要么改设计稿,要么改真实表",
|
||
table,
|
||
actual.join(", ")
|
||
))
|
||
.next(
|
||
"form.validate",
|
||
json!({ "enCode": "<功能编码>" }),
|
||
"体检设计稿自洽性",
|
||
)
|
||
}
|
||
|
||
/// 把 `$n` 占位符改成 `$n::text` + 类型 cast。
|
||
///
|
||
/// 🔴 必须加 `::text`:pglite 绑 `Option<String>`,
|
||
/// 若让 PG 把 `$1` 推断成 `timestamp` / `numeric`,会直接报
|
||
/// `cannot convert between the Rust type String and the Postgres type timestamp`。
|
||
///
|
||
/// 🔴 占位符必须**按完整 token 扫描**:`$1` 是 `$10` 的前缀,
|
||
/// 用字符串 find 会把 `$10` 改成 `$1::text0::text`。
|
||
///
|
||
/// 🔴 cast 靠 `param_columns`(占位符 ↔ 列名的一一映射),
|
||
/// **不猜**「第 n 个参数是哪一列」。
|
||
fn render_with_casts(
|
||
text: &str,
|
||
params: &[Value],
|
||
param_columns: &[String],
|
||
table: Option<&TableSchema>,
|
||
) -> String {
|
||
let mut out = String::with_capacity(text.len() + params.len() * 8);
|
||
let bytes = text.as_bytes();
|
||
let mut i = 0usize;
|
||
|
||
while i < bytes.len() {
|
||
if bytes[i] == b'$' {
|
||
// 读数字
|
||
let mut j = i + 1;
|
||
while j < bytes.len() && bytes[j].is_ascii_digit() {
|
||
j += 1;
|
||
}
|
||
if j > i + 1 {
|
||
let idx: usize = text[i + 1..j].parse().unwrap_or(0);
|
||
out.push_str(&text[i..j]);
|
||
out.push_str("::text");
|
||
if let Some(col) = param_columns.get(idx.saturating_sub(1)) {
|
||
out.push_str(cast_of_type(col, table));
|
||
}
|
||
i = j;
|
||
continue;
|
||
}
|
||
}
|
||
let ch_len = utf8_len(bytes[i]);
|
||
out.push_str(&text[i..i + ch_len]);
|
||
i += ch_len;
|
||
}
|
||
out
|
||
}
|
||
|
||
/// 取一个 UTF-8 字符的字节长度。
|
||
fn utf8_len(b: u8) -> usize {
|
||
if b < 0x80 {
|
||
1
|
||
} else if b >> 5 == 0b110 {
|
||
2
|
||
} else if b >> 4 == 0b1110 {
|
||
3
|
||
} else if b >> 3 == 0b11110 {
|
||
4
|
||
} else {
|
||
1
|
||
}
|
||
}
|
||
|
||
/// 按列名给出写值时的 cast。
|
||
fn cast_of_type(column: &str, table: Option<&TableSchema>) -> &'static str {
|
||
let Some(table) = table else {
|
||
return "";
|
||
};
|
||
// 先看模型里声明的数据类型
|
||
if let Some(def) = table.column_by_name(column) {
|
||
match def.data_type.to_lowercase().as_str() {
|
||
"int" | "integer" | "int2" | "int4" | "int8" | "bigint" | "smallint" => {
|
||
return "::integer"
|
||
}
|
||
"decimal" | "numeric" | "money" | "real" | "double" | "float" => return "::numeric",
|
||
"datetime" | "timestamp" | "date" | "time" => return "::timestamp",
|
||
"bool" | "boolean" => return "::boolean",
|
||
_ => {}
|
||
}
|
||
}
|
||
// 模型没说 ⇒ 按列名特征兜底
|
||
let lower = column.to_lowercase();
|
||
if lower.ends_with("_time") || lower.ends_with("_date") || lower.ends_with("time") {
|
||
return "::timestamp";
|
||
}
|
||
""
|
||
}
|
||
|
||
/// 值 ⇒ `Option<String>`(绑定用)。
|
||
///
|
||
/// 🔴 一律按**文本**传 —— 类型转换交给 SQL 里的 `::text` + cast 链。
|
||
fn params_as_text(values: &[Value]) -> Vec<Option<String>> {
|
||
values
|
||
.iter()
|
||
.map(|v| match v {
|
||
Value::Null => None,
|
||
Value::String(s) => Some(s.clone()),
|
||
Value::Number(n) => Some(n.to_string()),
|
||
Value::Bool(b) => Some(b.to_string()),
|
||
other => Some(other.to_string()),
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
/// 从一条 SQL 里取出列名。
|
||
fn columns_of_sql(text: &str) -> Vec<String> {
|
||
if let Some((_, rest)) = text.split_once(" (") {
|
||
if let Some((cols, _)) = rest.split_once(") VALUES") {
|
||
return cols.split(", ").map(|s| s.to_string()).collect();
|
||
}
|
||
}
|
||
if let Some((_, rest)) = text.split_once(" SET ") {
|
||
if let Some((sets, _)) = rest.split_once(" WHERE ") {
|
||
return sets
|
||
.split(", ")
|
||
.filter_map(|s| s.split(" = ").next())
|
||
.map(|s| s.to_string())
|
||
.collect();
|
||
}
|
||
}
|
||
Vec::new()
|
||
}
|
||
|
||
/// 找出子表节点对应的模型表。
|
||
fn resolve_sub_model<'a>(
|
||
model: &'a ModelSchema,
|
||
sub: &FieldNode,
|
||
) -> Option<&'a TableSchema> {
|
||
if let Some(name) = sub.table_name.as_deref() {
|
||
if let Some(t) = model.table(name) {
|
||
return Some(t);
|
||
}
|
||
}
|
||
for child in &sub.children {
|
||
if let Some(rt) = child.relation_table.as_deref() {
|
||
if let Some(t) = model.table(rt) {
|
||
return Some(t);
|
||
}
|
||
}
|
||
}
|
||
let subs = model.sub_tables();
|
||
if subs.len() == 1 {
|
||
Some(subs[0])
|
||
} else {
|
||
None
|
||
}
|
||
}
|
||
|
||
/// 从 payload 里取子表行数组。
|
||
fn sub_rows(payload: &Value, v_model: &str, table: &str) -> Option<Value> {
|
||
let obj = payload.as_object()?;
|
||
if let Some(v) = obj.get(v_model) {
|
||
return Some(v.clone());
|
||
}
|
||
for (k, v) in obj {
|
||
if k.eq_ignore_ascii_case(v_model) || k.eq_ignore_ascii_case(table) {
|
||
return Some(v.clone());
|
||
}
|
||
}
|
||
None
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
/// 🔴 比对必须能抓出「设计稿有、真实库没有」的列。
|
||
#[test]
|
||
fn compare_columns_finds_missing() {
|
||
let declared = vec!["f_id".to_string(), "f_room".to_string()];
|
||
let actual = vec!["f_id".to_string()];
|
||
let diff = compare_columns(&declared, &actual);
|
||
assert_eq!(diff.missing, vec!["f_room".to_string()]);
|
||
assert!(diff.extra.is_empty());
|
||
}
|
||
|
||
/// 大小写不敏感(PG 会折叠大小写)。
|
||
#[test]
|
||
fn compare_columns_is_case_insensitive() {
|
||
let declared = vec!["F_ID".to_string()];
|
||
let actual = vec!["f_id".to_string()];
|
||
let diff = compare_columns(&declared, &actual);
|
||
assert!(diff.missing.is_empty(), "不该报缺列: {:?}", diff.missing);
|
||
}
|
||
|
||
/// 🔴 占位符必须加 `::text` —— 否则 PG 推断成 timestamp/numeric 会报类型错。
|
||
#[test]
|
||
fn placeholders_get_text_cast() {
|
||
let out = render_with_casts(
|
||
"INSERT INTO t (a, b) VALUES ($1, $2)",
|
||
&[Value::String("x".into()), Value::String("y".into())],
|
||
&["a".to_string(), "b".to_string()],
|
||
None,
|
||
);
|
||
assert_eq!(out, "INSERT INTO t (a, b) VALUES ($1::text, $2::text)");
|
||
}
|
||
|
||
/// 数值列要加 `::numeric`。
|
||
#[test]
|
||
fn numeric_column_gets_numeric_cast() {
|
||
let model = ModelSchema::from_str(
|
||
r#"[{ "table": "t", "typeId": "1", "fields": [
|
||
{ "field": "F_Id", "columnName": "f_id", "primaryKey": 1 },
|
||
{ "field": "F_Price", "columnName": "f_price", "dataType": "decimal" }
|
||
]}]"#,
|
||
)
|
||
.unwrap();
|
||
let table = model.table("t").unwrap();
|
||
let out = render_with_casts(
|
||
"INSERT INTO t (f_id, f_price) VALUES ($1, $2)",
|
||
&[Value::String("a".into()), Value::String("9.9".into())],
|
||
&["f_id".to_string(), "f_price".to_string()],
|
||
Some(table),
|
||
);
|
||
assert!(
|
||
out.contains("$2::text::numeric"),
|
||
"数值列应带 ::numeric: {out}"
|
||
);
|
||
}
|
||
|
||
/// 🔴 **`$10` 不能被 `$1` 的替换误伤**。
|
||
///
|
||
/// 用 `str::find("$1")` 找位置会把 `$10` 当成 `$1` ⇒ 变成 `$1::text0::text`
|
||
/// ⇒ SQL 直接语法错。这是最难查的一类 bug(只在参数 ≥ 10 时出现)。
|
||
#[test]
|
||
fn ten_placeholders_are_not_corrupted_by_one() {
|
||
// 构造:INSERT INTO t (c1, ..., c10) VALUES ($1, ..., $10)
|
||
let mut text = String::from("INSERT INTO t (");
|
||
for i in 1..=10 {
|
||
if i > 1 {
|
||
text.push_str(", ");
|
||
}
|
||
text.push_str(&format!("c{i}"));
|
||
}
|
||
text.push_str(") VALUES (");
|
||
for i in 1..=10 {
|
||
if i > 1 {
|
||
text.push_str(", ");
|
||
}
|
||
text.push_str(&format!("${i}"));
|
||
}
|
||
text.push(')');
|
||
|
||
let params: Vec<Value> = (1..=10).map(|i| Value::String(format!("v{i}"))).collect();
|
||
let cols: Vec<String> = (1..=10).map(|i| format!("c{i}")).collect();
|
||
|
||
let out = render_with_casts(&text, ¶ms, &cols, None);
|
||
assert!(
|
||
out.contains("$10::text"),
|
||
"$10 应被完整替换: {out}"
|
||
);
|
||
assert!(
|
||
!out.contains("$1::text0"),
|
||
"$10 被 $1 的替换误伤了: {out}"
|
||
);
|
||
assert_eq!(
|
||
out.matches("::text").count(),
|
||
10,
|
||
"应有 10 处 ::text: {out}"
|
||
);
|
||
}
|
||
|
||
/// 值转 `Option<String>`:null ⇒ None。
|
||
#[test]
|
||
fn params_as_text_maps_null_to_none() {
|
||
let vals = params_as_text(&[
|
||
Value::Null,
|
||
Value::String("a".into()),
|
||
Value::Number(5.into()),
|
||
Value::Bool(true),
|
||
]);
|
||
assert_eq!(vals[0], None);
|
||
assert_eq!(vals[1].as_deref(), Some("a"));
|
||
assert_eq!(vals[2].as_deref(), Some("5"));
|
||
assert_eq!(vals[3].as_deref(), Some("true"));
|
||
}
|
||
|
||
/// 从 SQL 文本抽列名(INSERT / UPDATE 两种形态)。
|
||
#[test]
|
||
fn columns_of_sql_handles_both_shapes() {
|
||
let ins = "INSERT INTO t (a, b, c) VALUES ($1, $2, $3)";
|
||
assert_eq!(columns_of_sql(ins), vec!["a", "b", "c"]);
|
||
let upd = "UPDATE t SET a = $1, b = $2 WHERE id = $3";
|
||
assert_eq!(columns_of_sql(upd), vec!["a", "b"]);
|
||
}
|
||
|
||
/// 🔴 cast 必须靠 **列名**,不是靠「参数序号 = 模型字段序号」。
|
||
#[test]
|
||
fn cast_uses_param_columns_not_position() {
|
||
let model = ModelSchema::from_str(
|
||
r#"[{ "table": "t", "typeId": "1", "fields": [
|
||
{ "field": "F_Id", "columnName": "f_id", "primaryKey": 1 },
|
||
{ "field": "F_Amount", "columnName": "f_amount", "dataType": "decimal" }
|
||
]}]"#,
|
||
)
|
||
.unwrap();
|
||
let table = model.table("t").unwrap();
|
||
// 参数顺序与模型字段顺序**故意不同**:$1 是 f_amount,$2 是 f_id
|
||
let out = render_with_casts(
|
||
"INSERT INTO t (f_amount, f_id) VALUES ($1, $2)",
|
||
&[Value::String("9.9".into()), Value::String("id".into())],
|
||
&["f_amount".to_string(), "f_id".to_string()],
|
||
Some(table),
|
||
);
|
||
assert!(
|
||
out.contains("$1::text::numeric"),
|
||
"$1 是 f_amount,应带 ::numeric: {out}"
|
||
);
|
||
assert!(
|
||
out.contains("$2::text") && !out.contains("$2::text::numeric"),
|
||
"$2 是 f_id,不该带 ::numeric: {out}"
|
||
);
|
||
}
|
||
}
|