diff --git a/src/commands/dm/_validate.ts b/src/commands/dm/_validate.ts new file mode 100644 index 0000000..755f2c1 --- /dev/null +++ b/src/commands/dm/_validate.ts @@ -0,0 +1,316 @@ +/** + * commands/dm/_validate.ts — dm create step machine 校验 + * + * 镜像 web dataModel/Form.vue handleSubmit (L210-242) + 后端 DbTableController checkName (L92-112) 的前端校验 + * 让 dacli dm create 在发 API 之前暴露问题, AI 不用去浏览器试错 + * + * 设计原则 (2026-06-26 v0.11d+): + * - 不是复刻 web UI 行为 (drag/drop/click), 而是 mirror JNPF 业务规则 + * - 跟 form/_validate.ts + menu/_validate.ts 模式一致: 在发 API 前校验, 失败 → 聚合错误, 不发 API + * - 校验通过 → 1 次 create API call (不拆步骤) + * + * step 镜像对应: + * step 0: 基础信息 (镜像 web dataModel/Form.vue:42-61 schemas) + * - newTable 必填 + maxlength 50 + * - newTable 正则 (镜像 Form.vue:50) — 允许 _xxx 开头 + 大写字母 + * - tableName 必填 + maxlength 50 + * step 1: 字段定义 (镜像 web dataModel/Form.vue:174-209 exist() + L213/L215-216) + * - 字段数 ≥ 1 + * - 至少 1 个 primaryKey + * - 字段 vmodel 正则 (镜像 Form.vue:184) + * - dataType 白名单 {varchar, int, datetime, decimal, bigint, text} (镜像 Form.vue:19-26) + * - decimal dataLength 格式 ^\d+(?:,\d*)?$ (镜像 Form.vue:197) + * - 字段不重复 (镜像 Form.vue:191-196) + * - fieldName 必填 (镜像 Form.vue:202-206) + * step 2: 关键字 + 唯一性预校验 (镜像后端 DbTableController.java:92-112 checkName) + * - Java 关键字 (镜像后端 GenerateConstant.getJavaKeyword) + * - SQL 关键字 (镜像后端 GenerateConstant.getSqlKeyword) + * - 表名不重复 (后端 EXIST001 预校验) + */ + +export interface ValidationError { + /** 错误字段 (formId/字段名) */ + field?: string + /** 错误消息 (镜像 web 文案 + 后端 EXIST 码, AI 能对照) */ + message: string +} + +export interface StepValidation { + ok: boolean + step: 0 | 1 | 2 + /** step 名称 (用于日志) */ + stepName: string + errors: ValidationError[] +} + +/** 字段对象简化版 (供校验用) */ +export interface DmFieldLite { + field?: string + fieldName?: string + dataType?: string + dataLength?: string | number + primaryKey?: number | boolean + allowNull?: number | boolean + identity?: number | boolean + [k: string]: unknown +} + +/** + * newTable 正则 — 镜像 web dataModel/Form.vue:50 + * pattern: /(^_([A-Z0-9]_?)*$)|(^[A-Z](_?[A-Z0-9])*_?$)/i + * 允许: 大写字母/数字/下划线, 大写字母开头 OR _xxx 开头 + * 不允许: 小写字母开头 / 特殊字符 + * 注意: 与 form 字段 vmodel 正则 (允许小写) 略有不同! + * msg: '请输入正确的表名称' + */ +const NEWTABLE_REGEXP = /(^_([A-Z0-9]_?)*$)|(^[A-Z](_?[A-Z0-9])*_?$)/i + +/** 字段 vmodel 正则 — 镜像 web dataModel/Form.vue:184 + * reg: /(^_([a-z0-9]_?)*$)|(^[a-z](_?[a-z0-9])*_?$)/i + * 允许: 字母/数字/下划线, 小写字母开头 OR _xxx 开头 + * msg: '列名格式错误, 请重新输入' */ +const FIELD_REGEXP = /(^_([a-z0-9]_?)*$)|(^[a-z](_?[a-z0-9])*_?$)/i + +/** decimal dataLength 正则 — 镜像 web dataModel/Form.vue:185, 197 + * 格式: ^\d+(?:,\d*)?$ (例: 12 或 12,4) + * msg: '请输入数字' (decimal 类型) */ +const DECIMAL_LENGTH_REGEXP = /^\d+(?:,\d*)?$/ + +/** dataType 白名单 — 镜像 web dataModel/Form.vue:19-26 options */ +const VALID_DATA_TYPES = ['varchar', 'int', 'datetime', 'decimal', 'bigint', 'text'] + +/** Java 关键字子集 — 镜像后端 GenerateConstant.getJavaKeyword + * 完整列表见 jnpf/.../util/GenerateConstant.getJavaKeyword() */ +const JAVA_KEYWORDS = new Set([ + 'abstract', 'assert', 'boolean', 'break', 'byte', 'case', 'catch', 'char', 'class', + 'const', 'continue', 'default', 'do', 'double', 'else', 'enum', 'extends', 'final', + 'finally', 'float', 'for', 'goto', 'if', 'implements', 'import', 'instanceof', 'int', + 'interface', 'long', 'native', 'new', 'package', 'private', 'protected', 'public', + 'return', 'short', 'static', 'strictfp', 'super', 'switch', 'synchronized', 'this', + 'throw', 'throws', 'transient', 'try', 'void', 'volatile', 'while', +]) + +/** SQL 关键字子集 — 镜像后端 GenerateConstant.getSqlKeyword */ +const SQL_KEYWORDS = new Set([ + 'select', 'insert', 'update', 'delete', 'from', 'where', 'and', 'or', 'not', 'null', + 'create', 'drop', 'alter', 'table', 'index', 'view', 'database', 'schema', + 'primary', 'foreign', 'key', 'unique', 'check', 'default', 'constraint', + 'join', 'inner', 'left', 'right', 'outer', 'on', 'as', 'group', 'by', 'having', + 'order', 'limit', 'offset', 'union', 'distinct', 'all', 'any', 'in', 'between', + 'like', 'is', 'exists', 'case', 'when', 'then', 'else', 'end', + 'count', 'sum', 'avg', 'min', 'max', + 'int', 'integer', 'varchar', 'char', 'text', 'date', 'datetime', 'timestamp', 'decimal', + 'numeric', 'float', 'double', 'boolean', 'bigint', 'smallint', 'tinyint', +]) + +/** + * step 0: 基础信息校验 + * + * 镜像 web dataModel/Form.vue:42-61 schemas (newTable + tableName) + */ +export function validateBasicInfo(opts: { + table: string + tableName: string +}): StepValidation { + const errors: ValidationError[] = [] + + // 镜像 Form.vue:43-52 schemas[newTable] rules + if (!opts.table || !opts.table.trim()) { + errors.push({ field: 'table', message: '表名称不能为空' }) + } else if (opts.table.length > 50) { + errors.push({ field: 'table', message: '表名称不能超过 50 个字符' }) + } else if (!NEWTABLE_REGEXP.test(opts.table)) { + errors.push({ field: 'table', message: '请输入正确的表名称' }) + } + + // 镜像 Form.vue:54-58 schemas[tableName] + if (!opts.tableName || !opts.tableName.trim()) { + errors.push({ field: 'tableName', message: '表说明不能为空' }) + } else if (opts.tableName.length > 50) { + errors.push({ field: 'tableName', message: '表说明不能超过 50 个字符' }) + } + + return { + ok: errors.length === 0, + step: 0, + stepName: '基础信息', + errors, + } +} + +/** + * step 1: 字段定义校验 + * + * 镜像 web dataModel/Form.vue:174-209 exist() + L213 + L215-216 + */ +export function validateFields(opts: { + fields: DmFieldLite[] +}): StepValidation { + const errors: ValidationError[] = [] + + // 镜像 Form.vue:213 if (!fieldList.value.length) + if (!opts.fields || opts.fields.length === 0) { + errors.push({ field: 'fields', message: '请至少添加一个字段' }) + return { ok: false, step: 1, stepName: '字段定义', errors } + } + + // 镜像 Form.vue:215-216 至少 1 个 primaryKey + const hasPrimaryKey = opts.fields.some((f) => !!f.primaryKey) + if (!hasPrimaryKey) { + errors.push({ + field: 'fields.primaryKey', + message: '请选择一个字段作为主键', + }) + } + + // 镜像 Form.vue:174-209 exist() 字段级 7 项校验 + const seenFields = new Set() + opts.fields.forEach((f, i) => { + const row = i + 1 + // 镜像 L178-181 field 必填 + if (!f.field || !String(f.field).trim()) { + errors.push({ + field: `fields[${i}].field`, + message: `第${row}行列名不能为空`, + }) + } else if (!FIELD_REGEXP.test(String(f.field))) { + // 镜像 L184-190 field 正则 + errors.push({ + field: `fields[${i}].field`, + message: `第${row}行列名格式错误, 请重新输入`, + }) + } else if (seenFields.has(String(f.field))) { + // 镜像 L191-196 field 重复 + errors.push({ + field: `fields[${i}].field`, + message: `第${row}行列名'${f.field}'已重复`, + }) + } else { + seenFields.add(String(f.field)) + } + + // 镜像 L197-201 decimal dataLength 格式 + if (f.dataType === 'decimal' && f.dataLength !== undefined) { + if (!DECIMAL_LENGTH_REGEXP.test(String(f.dataLength))) { + errors.push({ + field: `fields[${i}].dataLength`, + message: `第${row}行请输入数字 (decimal 格式: 12 或 12,4)`, + }) + } + } + + // 镜像 L202-206 fieldName 必填 + if (!f.fieldName || !String(f.fieldName).trim()) { + errors.push({ + field: `fields[${i}].fieldName`, + message: `第${row}行说明不能为空`, + }) + } + + // 镜像 L19-26 options dataType 白名单 (新增, web 端用下拉框, 限制更严) + if (f.dataType && !VALID_DATA_TYPES.includes(String(f.dataType))) { + errors.push({ + field: `fields[${i}].dataType`, + message: `第${row}行数据类型必须为 ${VALID_DATA_TYPES.join('/')} 之一, 当前 ${f.dataType}`, + }) + } + }) + + return { + ok: errors.length === 0, + step: 1, + stepName: '字段定义', + errors, + } +} + +/** + * step 2: 关键字 + 唯一性预校验 + * + * 镜像后端 DbTableController.java:92-112 checkName + * - checkName: 表名 + 字段名不能是 Java/SQL 关键字 + * - 后端 createTable status 0 → EXIST001 (重复) + */ +export function validateKeywordAndUniqueness(opts: { + table: string + fields: DmFieldLite[] + /** 当前 dbLinkId 下已存在的表名 (供唯一性预校验) */ + existingTables?: string[] +}): StepValidation { + const errors: ValidationError[] = [] + + const tableLower = (opts.table || '').toLowerCase() + // 镜像后端 checkName L96-98 表名关键字 + if (JAVA_KEYWORDS.has(tableLower) || SQL_KEYWORDS.has(tableLower)) { + errors.push({ + field: 'table', + message: `表名称"${opts.table}"不能是 Java/SQL 关键字 (后端 checkName 镜像)`, + }) + } + + // 镜像后端 checkName L99-110 字段名关键字 + if (opts.fields && opts.fields.length > 0) { + const conflictFields: string[] = [] + opts.fields.forEach((f) => { + if (!f.field) return + const fieldLower = String(f.field).toLowerCase() + if (JAVA_KEYWORDS.has(fieldLower) || SQL_KEYWORDS.has(fieldLower)) { + conflictFields.push(String(f.field)) + } + }) + if (conflictFields.length > 0) { + errors.push({ + field: 'fields', + message: `列名${conflictFields.join(',')}不能是 Java/SQL 关键字 (后端 checkName 镜像)`, + }) + } + } + + // 镜像后端 EXIST001 表名重复 (后端会再查, 这是预校验) + if (opts.existingTables && opts.existingTables.length > 0) { + if (opts.existingTables.includes(opts.table)) { + errors.push({ + field: 'table', + message: `表名称"${opts.table}"已存在 (后端 EXIST001 预校验)`, + }) + } + } + + return { + ok: errors.length === 0, + step: 2, + stepName: '关键字与唯一性', + errors, + } +} + +/** 跑全部 step 校验, 返回聚合结果 */ +export function validateDmCreate(opts: { + table: string + tableName: string + fields: DmFieldLite[] + existingTables?: string[] +}): { + ok: boolean + steps: StepValidation[] +} { + const s0 = validateBasicInfo({ + table: opts.table, + tableName: opts.tableName, + }) + + const s1 = validateFields({ + fields: opts.fields, + }) + + const s2 = validateKeywordAndUniqueness({ + table: opts.table, + fields: opts.fields, + existingTables: opts.existingTables, + }) + + return { + ok: s0.ok && s1.ok && s2.ok, + steps: [s0, s1, s2], + } +} \ No newline at end of file diff --git a/src/commands/dm/create.ts b/src/commands/dm/create.ts index 12306ce..30f5352 100644 --- a/src/commands/dm/create.ts +++ b/src/commands/dm/create.ts @@ -14,6 +14,7 @@ import { preCheckDmCreate, handlePreCheckResult, loadContextSafe } from '../_pre import { runGuards, handleGuardResult } from '../_blindspot_guards.ts' import { loadAppContext } from '../app/context.ts' import { initWebapi, loadDataModel } from '../../webapi/dataModel.ts' +import { validateDmCreate, type DmFieldLite } from './_validate.ts' interface CreateOpts { table: string @@ -64,6 +65,10 @@ export function buildDmCreateCommand(): Command { return f }) + // v0.11d+ step machine 校验 (镜像 web dataModel/Form.vue handleSubmit L210-242 + 后端 DbTableController checkName L92-112) + // 在发 API 前暴露问题, 聚合错误, AI 不用试错 + runDmStepMachine(c, dbLinkId, { table: cleanTable, tableName: opts.tableName, fields: cleanFields as DmFieldLite[] }) + // P1.2: dm create pre-check (dbLinkId / 表重复) // 失败时 exit 2, 不进入 API 调用; 警告不阻断 handlePreCheckResult( @@ -152,12 +157,72 @@ export function buildDmCreateCommand(): Command { }) installAiHelpHook(cmd, { - purpose: '在指定业务库建物理表. fields JSON 必含 field/fieldName/dataType/dataLength.', + purpose: '在指定业务库建物理表. fields JSON 必含 field/fieldName/dataType/dataLength. v0.11d+ 加 step machine 校验 (3 step 镜像 web dataModel/Form.vue + 后端 DbTableController.checkName, 聚合错误, AI 不用去浏览器试错)', required: { '--table': '表名', '--tableName': '中文名', '--fields': '字段 JSON' }, optional: { '--dbLinkId': '业务库 id' }, - example: `dacli dm create --table=test_table --tableName="测试表" --fields='[{"field":"f_name","fieldName":"名称","dataType":"varchar","dataLength":"100","allowNull":0}]'`, - source: { api: 'POST /api/system/DataModel/{dbLinkId}/Table' }, - notes: ['autoIncrement/identity/columnName 已自动补全', '建表前确认 dbLinkId 对应业务库'], + example: `dacli dm create --table=test_table --tableName="测试表" --fields='[{"field":"f_name","fieldName":"名称","dataType":"varchar","dataLength":"100","allowNull":0,"primaryKey":1}]'`, + source: { api: 'POST /api/system/DataModel/{dbLinkId}/Table', ref: 'web/views/dataCenter/dataModel/Form.vue (后端: jnpf/.../DbTableController.java:262-280)' }, + notes: [ + 'v0.11d+ step machine (镜像 web dataModel/Form.vue handleSubmit + 后端 DbTableController.checkName):', + ' step 0 基础信息: table 正则 + tableName 必填 (镜像 Form.vue:50 正则 + L57 tableName)', + ' step 1 字段定义: 字段数 ≥ 1 + 至少 1 个 primaryKey + field 正则 + dataType 白名单 + decimal dataLength 格式 + 字段不重复 + fieldName 必填 (镜像 Form.vue:174-209 exist() + L213/L215-216)', + ' step 2 关键字+唯一性: Java/SQL 关键字 + 表名重复 (镜像后端 checkName L92-112 + EXIST001)', + 'autoIncrement/identity/columnName 已自动补全 (11 系统列: 9 核心 + f_description + f_modify_user)', + '建表前确认 dbLinkId 对应业务库', + ], }) return cmd } + +/** + * v0.11d+ step machine 校验 (3 步镜像 web dataModel/Form.vue + 后端 DbTableController.checkName) + * 在发 API 前暴露问题, 聚合错误一次报 + * + * 镜像原型: + * - web dataModel/Form.vue:42-61 schemas (newTable 正则 + tableName 必填) + * - web dataModel/Form.vue:174-209 exist() (字段级 7 项校验) + * - web dataModel/Form.vue:210-242 handleSubmit (≥1 字段 + ≥1 主键) + * - jnpf DbTableController.java:92-112 checkName (Java+SQL 关键字) + * - jnpf DbTableController.java:262-280 create (3 重返回码 SU001/EXIST001/DB019) + */ +async function runDmStepMachine( + c: JnpfClient, + dbLinkId: string, + opts: { table: string; tableName: string; fields: DmFieldLite[] }, +): Promise { + // 拉已存在表名 (供 step 2 唯一性预校验, 容错: 拉失败跳过) + let existingTables: string[] = [] + try { + const r = await c.get<{ data?: { list?: Array<{ table: string }> } | Array<{ table: string }> }>( + `/system/DataModel/${dbLinkId}/TableAll`, + ) + const data = r.data + if (Array.isArray(data)) { + existingTables = data.map((t) => t.table).filter(Boolean) + } else if (data && Array.isArray((data as { list?: unknown }).list)) { + existingTables = ((data as { list: Array<{ table: string }> }).list || []).map((t) => t.table).filter(Boolean) + } + } catch { + // 拉表列表失败不阻断 (step 2 跳过查重) + } + + const result = validateDmCreate({ + table: opts.table, + tableName: opts.tableName, + fields: opts.fields, + existingTables, + }) + + if (!result.ok) { + const allErrors = result.steps.flatMap((s) => + s.errors.map((e) => ({ step: s.step, stepName: s.stepName, ...e })), + ) + log.error(`✗ step machine 校验失败 (${allErrors.length} 个错误):`) + for (const e of allErrors) { + log.error(` [step ${e.step} ${e.stepName}] ${e.field || '?'}: ${e.message}`) + } + process.exit(1) + } + + log.info(`✓ step machine 校验通过 (3/3): table=${opts.table}, fields=${opts.fields.length}`) +}