@lark-apaas/miaoda-cli 0.1.0-alpha.4177673 → 0.1.0-alpha.465bdb8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,11 +20,15 @@ function ensureInnerSuccess(body) {
20
20
  if (code === "0" || code === "")
21
21
  return;
22
22
  const message = stripPgPrefix(body.error_msg ?? body.ErrorMessage ?? `dataloom API error [${code}]`);
23
+ // PRD 多语句失败:后端在 envelope 顶层透出 errorStatementIndex(从 0 起计),
24
+ // 单语句 / 单元执行不会带这个字段。下面的 AppError 都把它带上,让最终
25
+ // CLI JSON envelope 写到 error.statement_index。
26
+ const stmtIdx = typeof body.errorStatementIndex === "number" ? body.errorStatementIndex : undefined;
23
27
  // k_dl_1300002 是 PG 执行透传错误;error_msg 里常带 SQLSTATE,优先按 SQLSTATE 映射
24
28
  if (code === "k_dl_1300002") {
25
29
  const sqlstate = extractSqlstate(message);
26
30
  if (sqlstate && exports.SQLSTATE_MAP[sqlstate]) {
27
- throw new error_1.AppError(exports.SQLSTATE_MAP[sqlstate], message);
31
+ throw new error_1.AppError(exports.SQLSTATE_MAP[sqlstate], message, { statement_index: stmtIdx });
28
32
  }
29
33
  }
30
34
  // k_dl_1600000 是 dataloom 通用参数错误,不能整体映射;
@@ -44,10 +48,11 @@ function ensureInnerSuccess(body) {
44
48
  if (mapped) {
45
49
  throw new error_1.AppError(mapped.code, mapped.message ?? message, {
46
50
  next_actions: mapped.hint ? [mapped.hint] : undefined,
51
+ statement_index: stmtIdx,
47
52
  });
48
53
  }
49
54
  // 兜底:dataloom 未映射的 code 原样透传
50
- throw new error_1.AppError(`DB_API_${code}`, message);
55
+ throw new error_1.AppError(`DB_API_${code}`, message, { statement_index: stmtIdx });
51
56
  }
52
57
  /**
53
58
  * 剥掉 PG 透传错误的 "ERROR:" 前缀:CLI 输出本身就会前缀 "Error:",
@@ -27,16 +27,23 @@ function parseSqlResult(r) {
27
27
  recordCount: r.recordCount ?? rows.length,
28
28
  };
29
29
  }
30
- if (r.sqlType === "INSERT" || r.sqlType === "UPDATE" || r.sqlType === "DELETE" || r.sqlType === "DML") {
30
+ if (r.sqlType === "INSERT" ||
31
+ r.sqlType === "UPDATE" ||
32
+ r.sqlType === "DELETE" ||
33
+ r.sqlType === "MERGE" ||
34
+ r.sqlType === "DML") {
31
35
  const affected = r.affectedRows ?? extractRowCount(r.data);
32
36
  return {
33
37
  kind: "dml",
38
+ // 上面已 narrow,这里 cast 是为了 SqlType 联合里的 (string & {}) 让 TS 无法
39
+ // 自动收窄到字面量集合,不影响运行时安全
34
40
  sqlType: r.sqlType,
35
41
  affectedRows: affected,
36
42
  };
37
43
  }
38
- // DDL or unknown
39
- return { kind: "ddl" };
44
+ // DDL or unknown — sqlType 透传后端给的细粒度(CREATE_TABLE / DROP_TABLE / ...
45
+ // / 笼统 "DDL"),CLI JSON 输出直接当 command 用
46
+ return { kind: "ddl", sqlType: r.sqlType };
40
47
  }
41
48
  /** DML 的 data 通常是 `[{"rowCount": N}]`;兜底从这里读影响行数。 */
42
49
  function extractRowCount(data) {
@@ -214,7 +214,7 @@ async function resolveByName(appId, input) {
214
214
  error: {
215
215
  code: "FILE_NOT_FOUND",
216
216
  message: `File '${input}' does not exist`,
217
- hint: "Run `miaoda file ls` to verify file_name.",
217
+ hint: "Run `miaoda file ls` to see available files.",
218
218
  },
219
219
  };
220
220
  }
@@ -225,7 +225,7 @@ async function resolveByName(appId, input) {
225
225
  error: {
226
226
  code: "AMBIGUOUS_FILE_NAME",
227
227
  message: `Multiple files match name '${input}' (${String(matches.length)} found)`,
228
- hint: `Use absolute /path instead. Run \`miaoda file ls --name ${input}\` to see candidates.`,
228
+ hint: `Use path instead. Run \`miaoda file ls --name ${input}\` to see candidates.`,
229
229
  },
230
230
  };
231
231
  }
@@ -47,7 +47,8 @@ const index_1 = require("../../../api/db/index");
47
47
  * - --env 透传给后端 admin-inner(dbBranch 参数),不传时由后端按 workspace
48
48
  * 多环境状态兜底(多环境 → dev / 单环境 → main);后端检测到环境不存在
49
49
  * 会返 k_dl_1600000 + "Invalid DB Branch:...",CLI 侧映射为 MULTI_ENV_NOT_INITIALIZED
50
- * - 多条语句时只展示最后一条的结果(与 PRD 对齐);所有为 DDL 时展示批量摘要
50
+ * - 多语句行为对齐 PRD:每条 statement 一个独立结果元素,pretty 逐条 +
51
+ * 末尾汇总,--json 输出 data 数组。
51
52
  */
52
53
  async function handleDbSql(query, opts) {
53
54
  const appId = (0, shared_1.resolveAppId)(opts);
@@ -65,22 +66,16 @@ async function handleDbSql(query, opts) {
65
66
  (0, output_1.emit)("✓ No results");
66
67
  return;
67
68
  }
68
- // 全部 DDL 的批量场景:展示统计摘要(对齐 PRD `✓ 3 statements executed`)
69
- const allDdl = results.every((r) => r.sqlType === "DDL");
70
- if (allDdl && results.length > 1) {
71
- if ((0, output_1.isJsonMode)()) {
72
- (0, output_1.emit)({ data: { statements: results.length } });
73
- return;
74
- }
75
- const tty = (0, render_1.isStdoutTty)();
76
- (0, output_1.emit)(tty
77
- ? `✓ ${String(results.length)} statements executed`
78
- : `OK ${String(results.length)} statements executed`);
69
+ if (results.length === 1) {
70
+ renderSingle(results[0]);
71
+ return;
72
+ }
73
+ // 多语句:每条 statement 独立结果
74
+ if ((0, output_1.isJsonMode)()) {
75
+ (0, output_1.emit)({ data: results.map((r) => toMultiElement((0, index_1.parseSqlResult)(r))) });
79
76
  return;
80
77
  }
81
- // 其他场景:展示最后一条
82
- const last = results[results.length - 1];
83
- renderSingle(last);
78
+ renderMultiPretty(results);
84
79
  }
85
80
  /** 读取 stdin 并返回完整 SQL 文本(stdin 不是 TTY 即认为被 pipe)。 */
86
81
  async function readSql(inline) {
@@ -130,10 +125,11 @@ function renderSingle(raw) {
130
125
  }
131
126
  function toJson(parsed) {
132
127
  if (parsed.kind === "select") {
128
+ // PRD 单 SELECT:data 直接是行数组
133
129
  return { data: parsed.rows };
134
130
  }
135
131
  if (parsed.kind === "dml") {
136
- // PRD:DML 时 data = {command: "UPDATE", rows_affected: 3}
132
+ // PRD 单 DML:data = {command, rows_affected}
137
133
  return {
138
134
  data: {
139
135
  command: parsed.sqlType,
@@ -141,14 +137,66 @@ function toJson(parsed) {
141
137
  },
142
138
  };
143
139
  }
144
- return { data: { command: "DDL" } };
140
+ // PRD 单 DDL:data = {command, target?}。command 直接用后端给的细粒度
141
+ // (CREATE_TABLE / DROP_TABLE / ...),target 待后端给对象名后再加。
142
+ return { data: { command: parsed.sqlType } };
143
+ }
144
+ /**
145
+ * 多语句 --json 元素:与单 DDL/DML 形状一致,但 SELECT 包成
146
+ * {command:"SELECT", rows:[...]}(PRD 约定,避免数组里嵌套数组造成歧义)。
147
+ */
148
+ function toMultiElement(parsed) {
149
+ if (parsed.kind === "select") {
150
+ return { command: "SELECT", rows: parsed.rows };
151
+ }
152
+ if (parsed.kind === "dml") {
153
+ return { command: parsed.sqlType, rows_affected: parsed.affectedRows };
154
+ }
155
+ // DDL:用后端给的细粒度 command
156
+ return { command: parsed.sqlType };
157
+ }
158
+ /** 多语句 pretty:逐条 `Statement N: ...` + 末尾 `✓ N statements executed`。 */
159
+ function renderMultiPretty(results) {
160
+ const tty = (0, render_1.isStdoutTty)();
161
+ const lines = [];
162
+ for (let i = 0; i < results.length; i++) {
163
+ const parsed = (0, index_1.parseSqlResult)(results[i]);
164
+ const idx = i + 1;
165
+ if (parsed.kind === "select") {
166
+ const n = parsed.rows.length;
167
+ lines.push(`Statement ${String(idx)}: SELECT (${String(n)} row${n === 1 ? "" : "s"})`);
168
+ if (n > 0) {
169
+ const cols = collectColumns(parsed.rows);
170
+ const tbl = parsed.rows.map((r) => cols.map((c) => formatCell(r[c], tty)));
171
+ lines.push(tty ? (0, render_1.renderAlignedTable)(cols, tbl) : (0, render_1.renderTsv)(cols, tbl));
172
+ }
173
+ // 块间空行(最后一条不留)
174
+ if (i < results.length - 1)
175
+ lines.push("");
176
+ continue;
177
+ }
178
+ if (parsed.kind === "dml") {
179
+ const verb = dmlVerb(parsed.sqlType);
180
+ const n = parsed.affectedRows;
181
+ lines.push(`Statement ${String(idx)}: ${tty ? "✓ " : ""}${String(n)} row${n === 1 ? "" : "s"} ${verb}`);
182
+ continue;
183
+ }
184
+ // DDL
185
+ lines.push(`Statement ${String(idx)}: ${tty ? "✓ " : ""}DDL executed`);
186
+ }
187
+ // 汇总行:所有 statement 都跑完了
188
+ lines.push(tty
189
+ ? `✓ ${String(results.length)} statements executed`
190
+ : `OK ${String(results.length)} statements executed`);
191
+ (0, output_1.emit)(lines.join("\n"));
145
192
  }
146
193
  function dmlVerb(type) {
147
194
  switch (type) {
148
195
  case "INSERT": return "inserted";
149
196
  case "UPDATE": return "updated";
150
197
  case "DELETE": return "deleted";
151
- case "DML": return "affected"; // MERGE / 未识别子类的兜底
198
+ case "MERGE": return "merged";
199
+ case "DML": return "affected"; // 未识别子类的兜底
152
200
  }
153
201
  }
154
202
  /** 从第一行收集列顺序;缺失列保留空白(兼容稀疏行)。 */
@@ -103,13 +103,20 @@ async function resolveDeleteInputs(appId, paths, names) {
103
103
  }
104
104
  return { resolved, errors };
105
105
  }
106
- async function confirm(count) {
106
+ /**
107
+ * 删除前 TTY 二次确认。
108
+ * PRD 单文件场景下提示带具体路径:`? Delete '/path'? (y/N)`,
109
+ * 多文件场景汇总条数:`? Delete N files? (y/N)`。
110
+ * `firstInput` 是用户传入的第一个值(可能是 path 或 file_name),
111
+ * 单文件时直接展示给用户,方便核对目标。
112
+ */
113
+ async function confirm(count, firstInput) {
107
114
  const rl = node_readline_1.default.createInterface({
108
115
  input: process.stdin,
109
116
  output: process.stderr,
110
117
  });
111
118
  return new Promise((resolve) => {
112
- const prompt = count === 1 ? `? Delete 1 file? (y/N) ` : `? Delete ${String(count)} files? (y/N) `;
119
+ const prompt = count === 1 ? `? Delete '${firstInput}'? (y/N) ` : `? Delete ${String(count)} files? (y/N) `;
113
120
  rl.question(prompt, (answer) => {
114
121
  rl.close();
115
122
  resolve(answer.trim().toLowerCase() === "y");
@@ -129,7 +136,10 @@ async function handleFileRm(paths, opts) {
129
136
  // destructive guardrail
130
137
  const tty = (0, render_1.isStdoutTty)();
131
138
  if (tty && !opts.yes) {
132
- const ok = await confirm(totalCount);
139
+ // 单文件提示带具体目标方便用户核对;多文件传第一个 input 占位(实际只显示 N files)
140
+ // 上面已校验 totalCount > 0,paths/names 至少有一个非空
141
+ const firstInput = paths.length > 0 ? paths[0] : names[0];
142
+ const ok = await confirm(totalCount, firstInput);
133
143
  if (!ok) {
134
144
  throw new error_1.AppError("DESTRUCTIVE_CANCELLED", "Cancelled by user");
135
145
  }
@@ -173,6 +183,7 @@ async function handleFileRm(paths, opts) {
173
183
  input,
174
184
  code: "INTERNAL_ERROR",
175
185
  message: "Delete request returned success but file still exists (server-side issue)",
186
+ hint: undefined,
176
187
  };
177
188
  }
178
189
  catch (err) {
@@ -181,12 +192,14 @@ async function handleFileRm(paths, opts) {
181
192
  input,
182
193
  code: "FILE_NOT_FOUND",
183
194
  message: `File '${input}' does not exist at delete time`,
195
+ hint: "Run `miaoda file ls` to see available files.",
184
196
  };
185
197
  }
186
198
  return {
187
199
  input,
188
200
  code: "INTERNAL_ERROR",
189
201
  message: err instanceof Error ? err.message : "verification failed",
202
+ hint: undefined,
190
203
  };
191
204
  }
192
205
  }));
@@ -194,7 +207,9 @@ async function handleFileRm(paths, opts) {
194
207
  results.push({
195
208
  status: "error",
196
209
  input: c.input,
197
- error: { code: c.code, message: c.message },
210
+ error: c.hint
211
+ ? { code: c.code, message: c.message, hint: c.hint }
212
+ : { code: c.code, message: c.message },
198
213
  });
199
214
  }
200
215
  }
@@ -233,7 +248,12 @@ async function handleFileRm(paths, opts) {
233
248
  else
234
249
  lines.push(`FAIL\t${r.input}\t${r.error.message}`);
235
250
  }
236
- lines.push(`Deleted ${String(okCount)} of ${String(totalCount)} files`);
251
+ if (failCount === 0) {
252
+ lines.push(`Deleted ${String(okCount)} of ${String(totalCount)} files`);
253
+ }
254
+ else {
255
+ lines.push(`Deleted ${String(okCount)} of ${String(totalCount)} files (${String(failCount)} failed)`);
256
+ }
237
257
  (0, output_1.emit)(lines.join("\n"));
238
258
  }
239
259
  // 退出码:任一失败 → 1;全成功 → 0
@@ -5,12 +5,14 @@ class AppError extends Error {
5
5
  code;
6
6
  retryable;
7
7
  next_actions;
8
+ statement_index;
8
9
  constructor(code, message, opts) {
9
10
  super(message);
10
11
  this.name = "AppError";
11
12
  this.code = code;
12
13
  this.retryable = opts?.retryable ?? false;
13
14
  this.next_actions = opts?.next_actions ?? [];
15
+ this.statement_index = opts?.statement_index;
14
16
  }
15
17
  toJSON() {
16
18
  return {
@@ -18,6 +20,7 @@ class AppError extends Error {
18
20
  message: this.message,
19
21
  retryable: this.retryable,
20
22
  next_actions: this.next_actions,
23
+ statement_index: this.statement_index,
21
24
  };
22
25
  }
23
26
  }
@@ -44,6 +44,9 @@ function emitError(err) {
44
44
  if (info.next_actions && info.next_actions.length > 0) {
45
45
  errObj.hint = info.next_actions.join(" ");
46
46
  }
47
+ if (typeof info.statement_index === "number") {
48
+ errObj.statement_index = info.statement_index;
49
+ }
47
50
  process.stderr.write(JSON.stringify({ error: errObj }) + "\n");
48
51
  }
49
52
  else {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-apaas/miaoda-cli",
3
- "version": "0.1.0-alpha.4177673",
3
+ "version": "0.1.0-alpha.465bdb8",
4
4
  "description": "Miaoda 平台命令行工具,面向 Agent 调用",
5
5
  "type": "commonjs",
6
6
  "bin": {