- sspf-lowcode 纯计算建表 DDL 生成 + 模型回写(任务 #12/#13) - 内核 lowcode_crud/check/ddl:真实事务执行、落库前三重校验、动态建表后回写 f_tables_data - MCP 暴露 data.record.insert/update/delete(任务 #15) - 开发期 --seed-lowcode-demo 通道:建表 + 写 dev/release 快照,prod 档开库前闸门拒绝 - 修 f_delete_mark 类型 bug(INTEGER 列误写 bool 导致 PG 报错) - 修 pglite 0.2.7 在 stdout=/dev/null 时 boot 阶段 kevent 失败 -> exit(100) 残留 pid: open_db 开库前若 fd1 是字符设备,dup2 到匿名普通临时文件 - 文档漂移清理(tools/mod.rs 工具数、form.rs/model.rs 注释)
423 lines
14 KiB
Rust
423 lines
14 KiB
Rust
//! model —— 解析 baseline 的 `f_tables_data`(表结构定义)。
|
||
//!
|
||
//! ## 数据结构(实测)
|
||
//!
|
||
//! ```json
|
||
//! [
|
||
//! {
|
||
//! "table": "test_receivable",
|
||
//! "tableName": "应收费用主表",
|
||
//! "typeId": "1", // "1" = 主表, "0" = 子表
|
||
//! "relationTable": "",
|
||
//! "relationField": "",
|
||
//! "tableField": "",
|
||
//! "fields": [
|
||
//! {
|
||
//! "field": "F_Id", // 设计态字段名(权威)
|
||
//! "columnName": null, // 物理列名 —— **常常是 null**!
|
||
//! "fieldName": "主键", // 显示名
|
||
//! "dataType": "varchar",
|
||
//! "dataLength": "50",
|
||
//! "primaryKey": 1,
|
||
//! "allowNull": 0,
|
||
//! "autoIncrement": 0,
|
||
//! "identity": 0
|
||
//! }
|
||
//! ]
|
||
//! }
|
||
//! ]
|
||
//! ```
|
||
//!
|
||
//! ## 🔴 最重要的一条:`columnName` 不可信
|
||
//!
|
||
//! 实测数据里 `columnName` **大量为 null** ——「设计完还没建表」的商品态就是这样。
|
||
//! 所以物理列名必须从 `field` 推导(规则与 `form::v_model_to_column` 同一份实现):
|
||
//!
|
||
//! ```text
|
||
//! F_Id → f_id
|
||
//! F_Room → f_room
|
||
//! F_CertificatesType → f_certificatestype ← 注意没有下划线
|
||
//! ```
|
||
//!
|
||
//! ⇒ **不要指望「驼峰转下划线」**。真实列名最终以数据库 `information_schema` 为准,
|
||
//! 本模块只负责「设计态 → 预期列名」的推导与一致性校验。
|
||
|
||
use serde_json::{Map, Value};
|
||
|
||
use crate::form::v_model_to_column;
|
||
|
||
/// 解析失败原因。
|
||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
pub enum ModelError {
|
||
/// 不是数组。
|
||
NotAnArray,
|
||
/// 空数组。
|
||
Empty,
|
||
}
|
||
|
||
impl ModelError {
|
||
/// 机器可读码。
|
||
pub fn code(&self) -> &'static str {
|
||
match self {
|
||
ModelError::NotAnArray => "MODEL_NOT_ARRAY",
|
||
ModelError::Empty => "MODEL_EMPTY",
|
||
}
|
||
}
|
||
|
||
/// 人话说明。
|
||
pub fn message(&self) -> &'static str {
|
||
match self {
|
||
ModelError::NotAnArray => {
|
||
"f_tables_data 不是数组 —— 它应该是多张表的定义列表([{table,tableName,typeId,fields}])"
|
||
}
|
||
ModelError::Empty => "f_tables_data 是空数组,没有任何表定义",
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 一列的定义。
|
||
#[derive(Debug, Clone, PartialEq)]
|
||
pub struct ColumnDef {
|
||
/// 设计态字段名(`F_Id`)。**这是权威字段名**。
|
||
pub field: String,
|
||
/// 官方给的物理列名 —— 可能为 null(尚未建表)。
|
||
pub column_name: Option<String>,
|
||
/// 显示名(`主键`)。
|
||
pub field_name: String,
|
||
/// 数据类型(`varchar` / `int4` / `timestamp` …)。
|
||
pub data_type: String,
|
||
/// 长度(字符串形态,官方如此)。
|
||
pub data_length: String,
|
||
/// 是否主键。
|
||
pub primary_key: bool,
|
||
/// 是否允许 NULL。
|
||
pub allow_null: bool,
|
||
/// 是否自增。
|
||
pub auto_increment: bool,
|
||
}
|
||
|
||
impl ColumnDef {
|
||
/// 实际使用的物理列名:`columnName` 优先,否则从 `field` 推导。
|
||
///
|
||
/// 🔴 只在**非空**时才信 `columnName` —— 实测大量为 `null`。
|
||
pub fn resolved_column(&self) -> Option<String> {
|
||
match &self.column_name {
|
||
Some(c) if !c.is_empty() => Some(c.to_lowercase()),
|
||
_ => v_model_to_column(&self.field),
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 一张表的定义。
|
||
#[derive(Debug, Clone, PartialEq)]
|
||
pub struct TableSchema {
|
||
/// 物理表名。
|
||
pub table: String,
|
||
/// 显示名。
|
||
pub table_name: String,
|
||
/// `"1"` = 主表,`"0"` = 子表。
|
||
pub type_id: String,
|
||
/// 列定义(顺序即建表顺序)。
|
||
pub fields: Vec<ColumnDef>,
|
||
/// 🔴 **子表外键列**(`tableField`)—— 子表里指向主表主键的那一列。
|
||
///
|
||
/// ## 溯源
|
||
///
|
||
/// Java `FlowFormDataUtil.createMastTable()`:
|
||
/// ```java
|
||
/// String foreignKey = tableModel.getTableField();
|
||
/// GeneralInsertDSL dsl = insertInto(sqlTable).set(sqlTable.column(foreignKey)).toValue(foreignValue);
|
||
/// ```
|
||
///
|
||
/// ⇒ 外键列名**来自模型**,不是常量。实测 `test_details` 的 `tableField` 是
|
||
/// `F_Receivableid` ⇒ 物理列 `f_receivableid`,**不是** `f_foreign_id`。
|
||
///
|
||
/// 🔴 之前硬编码 `f_foreign_id` 会在真实数据上直接 `column does not exist`。
|
||
pub table_field: Option<String>,
|
||
/// 🔴 **主表关联字段**(`relationField`)—— 主表里被子表外键引用的那一列。
|
||
///
|
||
/// Java:`Object foreignValue = dataNewMap.get(tableModel.getRelationField());`
|
||
pub relation_field: Option<String>,
|
||
/// 本表关联到的主表名(`relationTable`;主表自身为空串)。
|
||
pub relation_table: Option<String>,
|
||
}
|
||
|
||
impl TableSchema {
|
||
/// 是否主表。
|
||
pub fn is_main(&self) -> bool {
|
||
self.type_id == "1"
|
||
}
|
||
|
||
/// 子表外键列的**物理列名**(`tableField` 推导)。
|
||
pub fn foreign_key_column(&self) -> Option<String> {
|
||
self.table_field
|
||
.as_deref()
|
||
.and_then(crate::form::v_model_to_column)
|
||
}
|
||
|
||
/// 主表关联列的**物理列名**(`relationField` 推导)。
|
||
pub fn relation_column(&self) -> Option<String> {
|
||
self.relation_field
|
||
.as_deref()
|
||
.and_then(crate::form::v_model_to_column)
|
||
}
|
||
|
||
/// 按 `F_xxx` 风格的设计态字段名找列(大小写不敏感)。
|
||
pub fn column_by_field(&self, field: &str) -> Option<&ColumnDef> {
|
||
self.fields
|
||
.iter()
|
||
.find(|c| c.field.eq_ignore_ascii_case(field))
|
||
}
|
||
|
||
/// 按物理列名找列(大小写不敏感)。
|
||
pub fn column_by_name(&self, name: &str) -> Option<&ColumnDef> {
|
||
self.fields.iter().find(|c| {
|
||
c.resolved_column()
|
||
.is_some_and(|r| r.eq_ignore_ascii_case(name))
|
||
})
|
||
}
|
||
|
||
/// 全部物理列名(已推导)。
|
||
pub fn column_names(&self) -> Vec<String> {
|
||
self.fields
|
||
.iter()
|
||
.filter_map(|c| c.resolved_column())
|
||
.collect()
|
||
}
|
||
|
||
/// 主键列名(可能为空 —— 设计态没标主键)。
|
||
pub fn primary_keys(&self) -> Vec<String> {
|
||
self.fields
|
||
.iter()
|
||
.filter(|c| c.primary_key)
|
||
.filter_map(|c| c.resolved_column())
|
||
.collect()
|
||
}
|
||
}
|
||
|
||
/// 解析后的模型(保留原始 JSON)。
|
||
#[derive(Debug, Clone)]
|
||
pub struct ModelSchema {
|
||
/// 原始 JSON —— 同构保存时原样写回。
|
||
pub raw: Value,
|
||
/// 表清单。
|
||
pub tables: Vec<TableSchema>,
|
||
}
|
||
|
||
impl ModelSchema {
|
||
/// 解析 `f_tables_data`。
|
||
pub fn parse(raw: &Value) -> Result<Self, ModelError> {
|
||
let Some(arr) = raw.as_array() else {
|
||
return Err(ModelError::NotAnArray);
|
||
};
|
||
if arr.is_empty() {
|
||
return Err(ModelError::Empty);
|
||
}
|
||
Ok(Self {
|
||
raw: raw.clone(),
|
||
tables: arr.iter().filter_map(parse_table).collect(),
|
||
})
|
||
}
|
||
|
||
/// 从 JSON 文本解析。
|
||
pub fn from_str(s: &str) -> Result<Self, ModelError> {
|
||
let v: Value = serde_json::from_str(s).map_err(|_| ModelError::NotAnArray)?;
|
||
Self::parse(&v)
|
||
}
|
||
|
||
/// 主表(`typeId == "1"`)。多个主表时取第一个。
|
||
pub fn main_table(&self) -> Option<&TableSchema> {
|
||
self.tables.iter().find(|t| t.is_main())
|
||
}
|
||
|
||
/// 按物理表名查找(大小写不敏感 —— 官方数据里有大小写混用)。
|
||
pub fn table(&self, name: &str) -> Option<&TableSchema> {
|
||
self.tables
|
||
.iter()
|
||
.find(|t| t.table.eq_ignore_ascii_case(name))
|
||
}
|
||
|
||
/// 子表清单。
|
||
pub fn sub_tables(&self) -> Vec<&TableSchema> {
|
||
self.tables.iter().filter(|t| !t.is_main()).collect()
|
||
}
|
||
}
|
||
|
||
fn parse_table(v: &Value) -> Option<TableSchema> {
|
||
let obj = v.as_object()?;
|
||
let table = obj.get("table").and_then(Value::as_str)?.trim().to_string();
|
||
if table.is_empty() {
|
||
return None;
|
||
}
|
||
Some(TableSchema {
|
||
table,
|
||
table_name: str_of(obj, "tableName"),
|
||
type_id: match obj.get("typeId") {
|
||
Some(Value::String(s)) => s.clone(),
|
||
Some(Value::Number(n)) => n.to_string(),
|
||
_ => "0".to_string(),
|
||
},
|
||
// 🔴 官方数据里这三个字段是空串(主表)或具体列名(子表)⇒ 空串视作「没有」。
|
||
table_field: opt_str(obj, "tableField"),
|
||
relation_field: opt_str(obj, "relationField"),
|
||
relation_table: opt_str(obj, "relationTable"),
|
||
fields: obj
|
||
.get("fields")
|
||
.and_then(Value::as_array)
|
||
.map(|a| a.iter().filter_map(parse_column).collect())
|
||
.unwrap_or_default(),
|
||
})
|
||
}
|
||
|
||
/// 取一个非空字符串字段(空串 ⇒ `None`)。
|
||
fn opt_str(obj: &Map<String, Value>, key: &str) -> Option<String> {
|
||
obj.get(key)
|
||
.and_then(Value::as_str)
|
||
.map(str::trim)
|
||
.filter(|s| !s.is_empty())
|
||
.map(str::to_string)
|
||
}
|
||
|
||
fn parse_column(v: &Value) -> Option<ColumnDef> {
|
||
let obj = v.as_object()?;
|
||
let field = obj.get("field").and_then(Value::as_str)?.trim().to_string();
|
||
if field.is_empty() {
|
||
return None;
|
||
}
|
||
Some(ColumnDef {
|
||
field,
|
||
column_name: obj
|
||
.get("columnName")
|
||
.and_then(Value::as_str)
|
||
.map(str::to_string),
|
||
field_name: str_of(obj, "fieldName"),
|
||
data_type: str_of(obj, "dataType"),
|
||
data_length: match obj.get("dataLength") {
|
||
Some(Value::String(s)) => s.clone(),
|
||
Some(Value::Number(n)) => n.to_string(),
|
||
_ => String::new(),
|
||
},
|
||
primary_key: truthy(obj.get("primaryKey")),
|
||
allow_null: truthy(obj.get("allowNull")),
|
||
auto_increment: truthy(obj.get("autoIncrement")),
|
||
})
|
||
}
|
||
|
||
/// 官方的布尔字段是 `0/1` 数字,但也见过 `true/false` 与 `"1"` 字符串。
|
||
fn truthy(v: Option<&Value>) -> bool {
|
||
match v {
|
||
Some(Value::Bool(b)) => *b,
|
||
Some(Value::Number(n)) => n.as_i64().unwrap_or(0) != 0,
|
||
Some(Value::String(s)) => s == "1" || s.eq_ignore_ascii_case("true"),
|
||
_ => false,
|
||
}
|
||
}
|
||
|
||
fn str_of(obj: &Map<String, Value>, key: &str) -> String {
|
||
obj.get(key)
|
||
.and_then(Value::as_str)
|
||
.unwrap_or("")
|
||
.to_string()
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use serde_json::json;
|
||
|
||
fn model() -> Value {
|
||
json!([
|
||
{
|
||
"table": "t_main", "tableName": "主表", "typeId": "1",
|
||
"fields": [
|
||
{"field":"F_Id","columnName":null,"fieldName":"主键","dataType":"varchar",
|
||
"dataLength":"50","primaryKey":1,"allowNull":0},
|
||
{"field":"F_Title","columnName":null,"fieldName":"标题","dataType":"varchar",
|
||
"dataLength":"200","primaryKey":0,"allowNull":1},
|
||
{"field":"F_Amount","columnName":"f_amount","fieldName":"金额","dataType":"numeric",
|
||
"dataLength":"","primaryKey":0,"allowNull":1}
|
||
]
|
||
},
|
||
{
|
||
"table": "t_child", "tableName": "子表", "typeId": "0",
|
||
"fields": [
|
||
{"field":"F_Item","columnName":null,"fieldName":"项目","dataType":"varchar",
|
||
"dataLength":"100","primaryKey":0,"allowNull":1}
|
||
]
|
||
}
|
||
])
|
||
}
|
||
|
||
#[test]
|
||
fn parses_tables_and_flags() {
|
||
let m = ModelSchema::parse(&model()).unwrap();
|
||
assert_eq!(m.tables.len(), 2);
|
||
assert_eq!(m.main_table().unwrap().table, "t_main");
|
||
assert_eq!(m.sub_tables().len(), 1);
|
||
assert!(m.main_table().unwrap().is_main());
|
||
}
|
||
|
||
/// 🔴 `columnName` 为 null 时必须从 `field` 推导 —— 实测数据大量如此。
|
||
#[test]
|
||
fn resolves_column_name_when_null() {
|
||
let m = ModelSchema::parse(&model()).unwrap();
|
||
let t = m.main_table().unwrap();
|
||
assert_eq!(t.column_names(), vec!["f_id", "f_title", "f_amount"]);
|
||
assert_eq!(
|
||
t.column_by_field("F_Title").unwrap().resolved_column().as_deref(),
|
||
Some("f_title")
|
||
);
|
||
}
|
||
|
||
/// 官方给了 `columnName` 时以它为准(可能与推导结果不同)。
|
||
#[test]
|
||
fn prefers_explicit_column_name() {
|
||
let m = ModelSchema::parse(&model()).unwrap();
|
||
let t = m.main_table().unwrap();
|
||
let c = t.column_by_field("F_Amount").unwrap();
|
||
assert_eq!(c.column_name.as_deref(), Some("f_amount"));
|
||
assert_eq!(c.resolved_column().as_deref(), Some("f_amount"));
|
||
}
|
||
|
||
#[test]
|
||
fn primary_keys_are_reported() {
|
||
let m = ModelSchema::parse(&model()).unwrap();
|
||
assert_eq!(m.main_table().unwrap().primary_keys(), vec!["f_id"]);
|
||
}
|
||
|
||
#[test]
|
||
fn rejects_wrong_shapes() {
|
||
assert_eq!(ModelSchema::parse(&json!({})).unwrap_err(), ModelError::NotAnArray);
|
||
assert_eq!(ModelSchema::parse(&json!([])).unwrap_err(), ModelError::Empty);
|
||
}
|
||
|
||
/// 主表可能缺失(用户只建了子表)—— 调用方要能处理。
|
||
#[test]
|
||
fn missing_main_table_is_none_not_panic() {
|
||
let m = ModelSchema::parse(&json!([
|
||
{"table":"t_child","typeId":"0","fields":[]}
|
||
]))
|
||
.unwrap();
|
||
assert!(m.main_table().is_none());
|
||
assert_eq!(m.sub_tables().len(), 1);
|
||
}
|
||
|
||
/// 布尔字段可能是 0/1、"1"、true —— 三种都要认。
|
||
#[test]
|
||
fn truthy_accepts_three_encodings() {
|
||
assert!(truthy(Some(&json!(1))));
|
||
assert!(truthy(Some(&json!("1"))));
|
||
assert!(truthy(Some(&json!(true))));
|
||
assert!(!truthy(Some(&json!(0))));
|
||
assert!(!truthy(Some(&json!("0"))));
|
||
assert!(!truthy(None));
|
||
}
|
||
|
||
#[test]
|
||
fn raw_is_preserved() {
|
||
let v = model();
|
||
let m = ModelSchema::parse(&v).unwrap();
|
||
assert_eq!(m.raw, v);
|
||
}
|
||
}
|