//! 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`]. use serde_json::{json, Value}; use sspf_lowcode::{ plan_create, rewrite_model, CreatePlan, DdlError, DdlOptions, FormSchema, ModelSchema, }; use sspf_mcp::adapter::ToolError; use sspf_core::db::Db; /// 建表的结果。 #[derive(Debug, Clone)] pub struct CreateTablesOutcome { /// 建出来的表(主表在前)。 pub tables: Vec, /// 哪些表是**已存在**因而跳过的。 pub skipped: Vec, /// 回写后的模型(`f_tables_data` 的新值)。 pub model: Value, /// 诊断信息。 pub notes: Vec, /// 实际执行的 DDL(dry-run 时给调用方看)。 pub ddl: Vec, /// 是否只是演练(没建表、没回写)。 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 { 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, 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 { // 🔴 建表选项来自**表单**(基线平台同款:`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 { 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, 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(), "非法标识符必须给出修复指引"); } }