feat(queries): 完成 M04 查询定义与版本激活

交付不可变查询版本、保存即生效与激活(D26),并带控制台列表筛选排序与试跑预览;补 RLS 下 current_version_no 回填迁移。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
unknownandCursor committed 2026-11-18 18:32:24 +08:00
1 parent 8c0335040f
commit 21cc721fcc
97 files changed
+13354 -153

No files matched your search

@@ -0,0 +1,78 @@
# Task Context Pack
## Task Goal
M04:受控查询草稿、不可变版本、只读预览与控制台(A-016~A-020;D24)。
## Current Slice Or Group
分析完成;用户已确认计划并要求执行全部切片。下一编码切片:**S1**。
## Requirement Source
`.task/2026-11-18/m04-queries/requirement.md`
## Implementation Source
`.task/2026-11-18/m04-queries/implementation-plan.md`
## Involved Modules Or Knowledge Areas
- 查询定义/版本;只读执行;M03 数据源 usable/熔断
- 控制台查询 UI(S5)
## Loaded Rules
- `AGENTS.md`;sy-standards(API 信封、错误、权限点、前端、红线、注释)
- Marionettist autonomous;原型确认停点;`risk_score>=4` 片际停
## Loaded Docs
- `docs/tasks/INDEX.md` M04;交接稿 A-02;`docs/decisions.md`;`docs/current/frontend-ui.md`
- M03 `assert_usable`/datasources API
## Allowed Modification Scope
按当前切片:见 implementation-plan 各 Slice Allowed Modification Scope。
## Forbidden Modification Scope
- 秘密入库/入日志;映射/报警/企微/场景正式采集;生产破坏性操作
- S4 确认前改 Vue 查询页
## Key Existing Entrypoints
- `services/watchman/src/watchman/services/datasources.py`:`assert_usable`、`list_references`、失败记账
- `services/watchman/src/watchman/api/routes/datasources.py`
- `services/watchman/src/watchman/auth/access.py`
- `web/apps/console/src/datasources/`(UI 模式参考)
- `.task/2026-11-17/m03-datasource/prototype/`(原型模式参考)
## Gate Policy
- selected / effective: autonomous
- finalApprovalRequired: true
## Validation Commands
```
cd services/watchman && uv run pytest
cd services/watchman && uv run alembic upgrade head
cd web/apps/console && pnpm test:unit && pnpm test:e2e && pnpm typecheck
```
## Assumptions
- 权限点 `watchman.query.*` 仅 admin
- 预览不进报警
- 正式采集留给 M08
## Risks
- SQL 注入与任意标识符;熔断绕过;版本可变回归
## Stop Conditions
- S4→S5:原型未确认
- high-risk/boundary-sensitive/risk>=4 片审未过
- 最终验收前不标 DONE_LOCAL(除非用户明确授权)
@@ -0,0 +1,168 @@
# M04 查询定义与采集 Implementation Plan
## Requirement Source
`.task/2026-11-18/m04-queries/requirement.md`(D24)
## Scope Summary
参数化 SQL 查询草稿、不可变版本发布、只读预览执行与控制台 UI。正式场景采集不在本轮。
## Involved Modules Or Areas
- `services/watchman`:模型、迁移、执行器、API、权限、数据源 references 回填。
- `web/apps/console`:仅 S4 确认后的查询页面。
- 不改 Casdoor 登录语义;不改熔断参数模型本身。
## Loaded Rules
- `AGENTS.md` 项目本地段;`.cursor/rules/sy-standards.mdc`
- Marionettist `gatePolicy.selected=autonomous`
## Loaded Docs
- `docs/tasks/INDEX.md` M04;交接稿 A-02;`docs/decisions.md` D14/D19/D22/D23/D24
- `docs/current/frontend-ui.md`
- M03:`assert_usable`、datasources routes/services
## Global Forbidden Scope
- 口令、连接串、加密密钥、预览全文入仓库/日志/证据。
- `.env.local`、`.cursor/mcp.json`
- 映射/规则/报警/企微/场景 Cron 正式采集
- 原型确认前的 Vue 查询页(S5 起允许)
- 生产库、`git reset --hard`、未授权自动 commit
## Execution Strategy
- Complexity: complex
- Default Execution: sequential
- Parallel Execution: not-needed
- Merge Owner: 主 Agent
## Slice Dependency Graph
| Slice | Depends On | Fallback Order | Gate Class | Risk Score |
| --- | --- | --- | --- | --- |
| S1 模型与版本 | 分析确认 | 1 | high-risk | 4 |
| S2 只读执行器 | S1 | 2 | high-risk | 4 |
| S3 API 与权限 | S1、S2 | 3 | boundary-sensitive | 4 |
| S4 HTML 原型 | S3 字段口径 | 4 | simple | 2 |
| S5 Vue 页面 | S4 用户确认 | 5 | standard | 3 |
| S6 整体验收 | S5 | 6 | boundary-sensitive | 3 |
## Implementation Slices
### Slice 1: 模型、迁移与不可变版本约束
#### Goal
平台库可按租户保存查询草稿与不可变版本;RLS 生效;版本内容更新路径在服务/测试层被拒绝。
#### Allowed Modification Scope
- `services/watchman/src/watchman/models/`
- `services/watchman/migrations/`
- `services/watchman/tests/` 本切片测试
#### Forbidden Scope
- API 路由、执行器真实连源、前端
#### Gate Class / Risk Score
high-risk / 4 — schema-migration
#### Validation
- `uv run pytest` 本切片测试;`alembic upgrade head`
#### Done Criteria
- 表与 RLS 就绪;版本行内容不可被服务辅助函数更新(测试覆盖)
### Slice 2: 只读执行器
#### Goal
对给定 SQL 模板+参数+限制在 usable 数据源上只读执行;空/非法类型/失败三分;绑定防注入。
#### Allowed Modification Scope
- `services/watchman/src/watchman/queries/`(或等价包)
- `services/watchman/src/watchman/services/` 执行相关
- 测试;必要时薄改 datasources 记账调用
#### Forbidden Scope
- 前端;发布 API 完整面
#### Gate Class / Risk Score
high-risk / 4 — device/datasource communication, injection
#### Validation
- 单元/集成:绑定、超时、行数、空结果、类型不匹配、参数含 SQL 片段不注入
### Slice 3: API、权限、引用回填
#### Goal
CRUD/启停/publish/版本/preview/references;四权限点;审计;数据源 references 列查询。
#### Allowed Modification Scope
- `api/routes/`、`auth/access.py`、`services/`、`api/app.py` 注册
- datasources `list_references` 回填
- 测试
#### Gate Class / Risk Score
boundary-sensitive / 4 — permissions, public API
#### Validation
- API 测试:权限拒绝、发布递增、版本只读、预览三分、信封
### Slice 4: HTML 原型
#### Goal
静态原型覆盖列表/编辑/版本/预览/角色门,供确认。
#### Allowed Modification Scope
- `.task/2026-11-18/m04-queries/prototype/` 仅
#### Gate Class / Risk Score
simple / 2
#### Stop
用户确认前不开始 S5。
### Slice 5: Vue 控制台
#### Goal
按确认原型与 D22 实现查询页与 e2e/单测。
#### Allowed Modification Scope
- `web/apps/console/**` 查询相关、导航、四语言、e2e
#### Gate Class / Risk Score
standard / 3
### Slice 6: 模块整体 review 与正式测试
#### Goal
独立 review、修复、pytest/unit/Playwright 证据、主 Agent 验收(DONE_LOCAL 仅用户最终确认后)。
#### Gate Class / Risk Score
boundary-sensitive / 3
+46
View File
@@ -0,0 +1,46 @@
# Task Intake Result
## Task Type
feature。Tier L(只读执行、注入防护、迁移、不可变版本、跨前后端)。
## Current Understanding
- M03 DONE_LOCAL。推进 M04:受控查询定义、参数/输出契约、只读执行、预览与配套 UI(A-016~A-020)。
- 用户确认:参数化 SQL 模板(A);不可变查询版本本轮交付(2b);正式定时/场景采集留给 M08。
- 正式 Vue 前须 HTML 原型确认(与 M03/D21 同模式)。
- 执行须经 M03 `assert_usable`/熔断记账,不得绕过。
## Gate Policy
- config/default: balanced
- allowTaskOverride: true
- recommended: balanced
- selected: autonomous
- reason or override reason: 用户在 Marionettist 入口明确选择 autonomous。
- effective: autonomous
- finalApprovalRequired: true
说明:autonomous 不取消分析→编码门禁、最终验收、`gateClass: high-risk|boundary-sensitive`、critic、显式停点、危险命令,以及 `risk_score >= 4`。HTML 原型确认为 S5 前显式停点。用户于 2026-11-18 确认计划并要求执行全部 todos,视为越过分析→编码门禁。
## Blocking Questions
已关闭:
1. 查询正文 = 参数化 SQL 模板。
2. M04 交付不可变查询版本(publish/只读历史);正式采集留给 M08。
## Non-blocking Assumptions
- 权限仅 `watchman-admin`,权限点 `watchman.query.{read,write,publish,preview}`。
- 预览不进报警/通知。
- 定义/版本 references 先空列表;数据源 references 可回填查询引用。
- 标识符白名单用于不可绑定对象名;不靠 SELECT 前缀。
## Recommended Next Step
编码 S1(模型与迁移)。
## Suggested Prompt For Next Step
按 `implementation-plan.md` Slice 1 实现 query_definitions/query_versions 与 RLS/不可变约束测试。
@@ -0,0 +1,79 @@
# M04 查询定义 · 静态 HTML 原型(S4)
**状态:待维护者确认,确认前不得据此编写 Vue 页面。** 未经确认信息架构、按钮位置与各预览状态,不改正式 Vue 应用,也不动后端。
## 如何打开
直接用浏览器打开本目录的 `index.html`(双击即可)。单文件,无构建、无 CDN、无网络请求。
## 控件说明
顶部黄色虚线条「原型切换」不属于未来产品,只用于评审。
- **角色**:管理者 / 处理者 / 查看者。只有管理者能进入查询界面;处理者和查看者只看到「无法进入查询」(后端对应 42000 并带权限点)。
- **画面**(仅管理者):空列表、列表、新建草稿、编辑草稿、编辑(已停用)、版本只读。
- **预览结果**:未试跑 / 试跑中 / 成功 / 空结果 / 非法类型 / 失败 / 已停用 / 熔断中。点按钮立即展示该结果,并让之后点页脚「试跑预览」得到同一结果(先显示约 1 秒试跑中)。
- **失败子类型**:超时 / 连接失败 / SQL 语法错误(三类分开展示;连接失败注明计入熔断统计)。
- 编辑页中的名称、SQL、参数、输出、标识符、限制可以真的改;「保存草稿」「发布」「停用/启用」只修改本页内存数据,刷新即还原。
## 原型包含
| 画面 | 内容 |
| --- | --- |
| 门禁 | 非管理者看到拒绝页,无列表、无表单 |
| 空列表 | 说明 + 表格上方「新建」 |
| 列表 | 名称、数据源、状态、最新版本、更新时间、行内「打开」「预览」;已停用行「预览」置灰 |
| 新建/编辑草稿 | 名称、用途说明、数据源(已停用的灰显)、SQL 模板(示例 `:line_code`,实时标出未声明参数)、参数 schema(名称/类型/必填/默认值)、输出 schema(名称/类型)、允许标识符(标签)、`timeout_ms`、`max_rows`、状态、试跑预览区、版本列表、引用占位 |
| 版本只读 | 冻结的 SQL、参数、输出、标识符、限制;可试跑;无保存、无发布 |
| 预览结果 | 成功(样例行,示例脱敏列)、空结果、非法类型(契约不符明细)、失败(超时/连接/语法)、已停用、熔断中 |
| 发布 | 页脚「发布」弹出确认;有未保存修改时先提示保存;成功后版本列表新增 vN |
页脚按钮(居中、在滚动区外):
- 新建:返回列表、保存草稿、发布(置灰,需先保存)、试跑预览(置灰,需先保存)。
- 编辑草稿:返回列表、保存草稿、发布、停用/启用、试跑预览。
- 版本只读:返回列表、返回草稿、试跑预览。
- 列表页「新建」在表格上方;行内「打开」「预览」留在行内;版本列表行内「打开」。依据 `docs/current/frontend-ui.md`(D22)。
## 原型不包含
- 真实请求、真实数据源或口令;所有数据虚构,数据源名称无真实地址。
- 结构化表/字段选择器、任意脚本、字段映射、规则、报警、通知、场景定时采集。
- 非数据库数据源、查询物理删除、列表分页/筛选、审计页。
- 引用的具体内容(查询侧恒为「尚无引用」)。
- 服务端上限的真实值(页面里的 30000/1000 仅为示意)。
## 按钮与未来 Vue(Element Plus)对应
| 原型 | Vue 实现 |
| --- | --- |
| 列表「新建」 | `el-button type="primary"`,放在 `el-table` 上方 |
| 列表/版本表 | `el-table`;行内「打开」「预览」用 `el-button link` |
| 状态 | `el-tag` 或 `el-badge`;停用行「预览」`disabled` |
| 表单 | `el-form` + `el-form-item`、`el-input`、`el-input type="textarea"`、`el-select`、`el-input-number` |
| SQL 模板 | `el-input type="textarea"` 等宽字体(如需高亮另行评审,不引入新依赖前先问) |
| 参数/输出 schema | 可编辑 `el-table` + `el-input`/`el-select`/`el-checkbox`;行内删除 |
| 允许标识符 | `el-tag closable` + `el-input` 回车添加 |
| 页脚 | 滚动区外的固定区,`el-button` 居中;保存草稿 `primary`,发布 `plain`,停用 `type="danger" plain`,其余默认 |
| 发布确认 | `ElMessageBox.confirm` |
| 预览结果 | `el-alert`(成功/警告/错误)+ `el-table` 展示样例;试跑中用 `v-loading` |
| 无权限 | 空状态页(`el-empty`);真正权限由后端判定,前端隐藏不算安全控制 |
| 原型切换条、「原型本地模拟」提示、`正式版本进行删除` 标注 | 正式版全部删除 |
视觉 token:主色 `#5e6ad2`、圆角 8px、基础字号 13.5px。
## 请维护者确认
1. 预览使用「已保存草稿」还是「表单当前内容」?原型按已保存草稿,有未保存修改时给提示。
2. 查询停用后:「试跑预览」按钮仍可点并明确拒绝(原型做法),还是直接置灰?停用时「发布」是否允许?原型未限制。
3. 发布入口只在页脚(原型做法),版本区不放第二个发布按钮,是否同意?
4. 输出契约只有名称和类型,敏感列脱敏策略未设字段;原型只用固定示例遮盖 `operator_name`。是否需要「脱敏」列?
5. 标识符白名单的 SQL 占位语法未定;原型只展示允许列表。
6. 版本只读页面包含数据源名,并以 `详情 / 版本 vN` 作为面包屑,是否合适?
7. 预览成功样例固定 3 行;超出 `max_rows` 的截断提示未做。是否需要?
8. 失败子类型中,超时是否计入熔断,以后端口径为准,原型未声明。
## 约束
- 所有数据均为虚构;不含真实口令;不含 API 调用。
- 不改 Vue 应用与后端,不提交 git。
@@ -0,0 +1,842 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Watchman M04 查询定义 · 静态原型(S4)</title>
<style>
:root {
--primary: #5e6ad2;
--primary-soft: #eef0fb;
--text: #1f2328;
--text-2: #59636e;
--muted: #8b949e;
--surface: #ffffff;
--soft: #f6f8fa;
--border: #d0d7de;
--border-2: #eaeef2;
--ok: #1a7f37;
--ok-bg: #e9f6ec;
--warn: #9a6700;
--warn-bg: #fff8e1;
--err: #cf222e;
--err-bg: #fdecee;
--radius: 8px;
--font: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
}
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; }
body { font-family: var(--font); font-size: 13.5px; color: var(--text); background: var(--soft); line-height: 1.55; }
button, input, select, textarea { font: inherit; color: inherit; }
[hidden] { display: none !important; }
/* ---- prototype toolbar (not part of product) ---- */
.proto {
background: #fffbe6; border-bottom: 1px dashed #d4b106; padding: 8px 16px;
display: flex; flex-wrap: wrap; gap: 8px 20px; align-items: center; font-size: 12.5px;
}
.proto-title { font-weight: 600; color: #7a5b00; }
.proto-group { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.proto-group > .lbl { color: var(--text-2); margin-right: 2px; }
.proto-btn {
border: 1px solid var(--border); background: var(--surface); border-radius: 6px;
padding: 2px 9px; cursor: pointer; font-size: 12.5px;
}
.proto-btn:hover { border-color: var(--primary); color: var(--primary); }
.proto-btn.on { background: var(--primary); border-color: var(--primary); color: #fff; }
.proto-note { flex-basis: 100%; color: #7a5b00; }
.proto select { border: 1px solid var(--border); border-radius: 6px; padding: 2px 6px; background: #fff; font-size: 12.5px; }
/* ---- shell ---- */
.shell { display: flex; height: calc(100vh - 120px); min-height: 520px; }
.side { width: 196px; flex: none; background: var(--surface); border-right: 1px solid var(--border-2); padding: 14px 10px; }
.brand { font-weight: 700; font-size: 16px; padding: 4px 10px 14px; letter-spacing: .3px; }
.nav-item { padding: 7px 10px; border-radius: 6px; color: var(--text-2); }
.nav-item.cur { background: var(--primary-soft); color: var(--primary); font-weight: 600; }
.nav-item.off { color: var(--muted); }
.main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
.top { height: 48px; flex: none; background: var(--surface); border-bottom: 1px solid var(--border-2);
display: flex; align-items: center; justify-content: space-between; padding: 0 20px; }
.pagefoot { flex: none; background: var(--surface); border-top: 1px solid var(--border-2);
display: flex; align-items: center; justify-content: center; flex-wrap: wrap; gap: 8px; padding: 12px 20px; }
.list-actions { display: flex; justify-content: flex-end; margin-bottom: 12px; }
.crumb { color: var(--text-2); }
.crumb b { color: var(--text); font-weight: 600; }
.who { color: var(--text-2); display: flex; align-items: center; gap: 8px; }
.tag { display: inline-block; padding: 0 8px; border-radius: 10px; font-size: 12px; line-height: 20px; background: var(--primary-soft); color: var(--primary); }
.tag.grey { background: var(--soft); color: var(--text-2); border: 1px solid var(--border-2); }
.tag.ok { background: var(--ok-bg); color: var(--ok); }
.tag.warn { background: var(--warn-bg); color: var(--warn); }
.content { flex: 1; overflow: auto; padding: 20px; }
.local-banner { background: var(--primary-soft); border: 1px solid #d5d9f5; color: #3f49a8; border-radius: var(--radius);
padding: 7px 12px; margin-bottom: 14px; font-size: 12.5px; }
.flash { border-radius: var(--radius); padding: 8px 12px; margin-bottom: 14px; border: 1px solid; font-size: 13px; }
.flash.ok { background: var(--ok-bg); border-color: #b7e0c2; color: #145c2a; }
.flash.warn { background: var(--warn-bg); border-color: #f1dc9a; color: var(--warn); }
.flash.bad { background: var(--err-bg); border-color: #f4b8be; color: #8e1a23; }
.card { background: var(--surface); border: 1px solid var(--border-2); border-radius: var(--radius); padding: 16px 18px; margin-bottom: 16px; }
.card h3 { margin: 0 0 12px; font-size: 14.5px; display: flex; align-items: center; justify-content: space-between; gap: 10px; }
.card h3 .sub { font-weight: 400; font-size: 12px; color: var(--muted); }
.btn { border: 1px solid var(--border); background: var(--surface); border-radius: 6px; padding: 5px 14px; cursor: pointer; }
.btn:hover:not(:disabled) { border-color: var(--primary); color: var(--primary); }
.btn.primary { background: var(--primary); border-color: var(--primary); color: #fff; }
.btn.primary:hover:not(:disabled) { background: #4f5bc4; color: #fff; }
.btn.outline { border-color: var(--primary); color: var(--primary); }
.btn.danger { color: var(--err); }
.btn.danger:hover:not(:disabled) { border-color: var(--err); color: var(--err); }
.btn.sm { padding: 1px 8px; font-size: 12.5px; }
.btn:disabled { color: var(--muted); background: var(--soft); border-color: var(--border); cursor: not-allowed; }
.btn.link { border: 0; background: none; color: var(--primary); padding: 1px 6px; }
.btn.link.danger { color: var(--err); }
.btn.link:disabled { color: var(--muted); background: none; }
table { width: 100%; border-collapse: collapse; }
th { text-align: left; font-weight: 600; color: var(--text-2); background: var(--soft); padding: 9px 12px; border-bottom: 1px solid var(--border-2); white-space: nowrap; }
td { padding: 10px 12px; border-bottom: 1px solid var(--border-2); vertical-align: middle; }
tr.hl td { background: #fafbff; }
tr.off td { color: var(--muted); }
.mono { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12.5px; }
.table-wrap { overflow-x: auto; border: 1px solid var(--border-2); border-radius: var(--radius); background: var(--surface); }
.table-wrap table th:first-child, .table-wrap table td:first-child { padding-left: 16px; }
.table-wrap.inner table td { padding: 6px 10px; }
.ops { white-space: nowrap; }
.tbl-tools { display: flex; justify-content: flex-end; margin: -4px 0 8px; }
.status { display: inline-flex; align-items: center; gap: 6px; }
.dot { width: 7px; height: 7px; border-radius: 50%; background: var(--ok); }
.status.off .dot { background: var(--muted); }
.empty { text-align: center; padding: 56px 20px; background: var(--surface); border: 1px dashed var(--border); border-radius: var(--radius); }
.empty h3 { margin: 0 0 6px; font-size: 15px; }
.empty p { margin: 0 0 14px; color: var(--text-2); }
.empty.sm { padding: 18px 20px; }
.empty.sm p { margin: 0; }
.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px 24px; max-width: 820px; }
.field { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
.field.full { grid-column: 1 / -1; }
.field > label { color: var(--text-2); font-size: 12.5px; }
.req { color: var(--err); margin-left: 2px; }
input[type=text], input[type=number], select, textarea {
border: 1px solid var(--border); border-radius: 6px; padding: 6px 10px; background: var(--surface); width: 100%; outline: none; }
input:focus, select:focus, textarea:focus { border-color: var(--primary); box-shadow: 0 0 0 2px var(--primary-soft); }
input:disabled, select:disabled, textarea:disabled { background: var(--soft); color: var(--text-2); cursor: not-allowed; }
.table-wrap.inner input[type=text], .table-wrap.inner select { padding: 3px 8px; }
textarea.sql { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12.5px; line-height: 1.6; resize: vertical; }
pre.sql { margin: 0; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12.5px; line-height: 1.6;
background: var(--soft); border: 1px solid var(--border-2); border-radius: 6px; padding: 10px 12px; white-space: pre-wrap; }
.hint { color: var(--muted); font-size: 12px; }
.drop-later { color: #7a5b00; }
.check { display: flex; align-items: center; gap: 8px; }
.chips { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-top: 6px; }
.chip { display: inline-flex; align-items: center; gap: 4px; padding: 0 8px; line-height: 22px; border-radius: 4px; font-size: 12px;
border: 1px solid var(--border); background: var(--soft); font-family: ui-monospace, Consolas, monospace; }
.chip.ok { background: var(--ok-bg); border-color: #b7e0c2; color: #145c2a; }
.chip.bad { background: var(--err-bg); border-color: #f4b8be; color: #8e1a23; }
.chip.dim { color: var(--muted); }
.chip button { border: 0; background: none; cursor: pointer; color: var(--muted); padding: 0 2px; }
.chip button:hover { color: var(--err); }
.ident-add { display: flex; gap: 8px; margin-top: 10px; max-width: 420px; }
.note { border-radius: var(--radius); padding: 8px 12px; font-size: 12.5px; background: var(--soft); border: 1px solid var(--border-2); color: var(--text-2); }
.note.warn { background: var(--warn-bg); border-color: #f1dc9a; color: var(--warn); }
.pv-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px 20px; max-width: 820px; margin-bottom: 12px; }
.pv-target { margin-bottom: 10px; color: var(--text-2); font-size: 12.5px; }
.result { border-radius: var(--radius); padding: 12px 14px; border: 1px solid; margin-top: 12px; }
.result .r-title { font-weight: 600; margin-bottom: 2px; }
.result .r-body { font-size: 13px; }
.result .r-meta { margin-top: 6px; font-size: 12px; opacity: .85; }
.result .r-table { margin-top: 10px; background: #fff; color: var(--text); }
.result .r-table td, .result .r-table th { white-space: nowrap; }
.result.ok { background: var(--ok-bg); border-color: #b7e0c2; color: #145c2a; }
.result.bad { background: var(--err-bg); border-color: #f4b8be; color: #8e1a23; }
.result.pend { background: var(--primary-soft); border-color: #d5d9f5; color: #3f49a8; }
.result.warn { background: var(--warn-bg); border-color: #f1dc9a; color: var(--warn); }
.result.grey { background: var(--soft); border-color: var(--border); color: var(--text-2); }
.spin { display: inline-block; width: 12px; height: 12px; border: 2px solid #c3c8f0; border-top-color: var(--primary); border-radius: 50%; animation: sp .8s linear infinite; vertical-align: -2px; margin-right: 6px; }
@keyframes sp { to { transform: rotate(360deg); } }
.focus { outline: 2px solid var(--primary-soft); border-color: var(--primary); }
.kv { display: grid; grid-template-columns: 96px 1fr; gap: 4px 12px; font-size: 13px; }
.kv dt { color: var(--muted); } .kv dd { margin: 0; }
.modal-mask { position: fixed; inset: 0; background: rgba(31,35,40,.4); display: flex; align-items: center; justify-content: center; z-index: 10; }
.modal { background: #fff; border-radius: var(--radius); padding: 18px 20px; width: 400px; max-width: 90vw; box-shadow: 0 8px 28px rgba(0,0,0,.18); }
.modal h3 { margin: 0 0 8px; font-size: 15px; }
.modal p { margin: 0 0 16px; color: var(--text-2); }
.modal .row { display: flex; justify-content: flex-end; gap: 8px; }
</style>
</head>
<body>
<div class="proto" id="proto">
<span class="proto-title">原型切换</span>
<div class="proto-group"><span class="lbl">角色</span><span id="p-roles"></span></div>
<div class="proto-group"><span class="lbl">画面</span><span id="p-screens"></span></div>
<div class="proto-group"><span class="lbl">预览结果</span><span id="p-results"></span></div>
<div class="proto-group" id="p-fsub-wrap"><span class="lbl">失败子类型</span><select id="p-fsub"></select></div>
<div class="proto-note">此条仅用于评审,不属于未来产品。所有数据均为虚构,页面不发送任何网络请求,不含真实密码或地址。点「预览结果」按钮会立即展示该结果,并让页脚「试跑预览」之后得到同一结果。正式版本进行删除</div>
</div>
<div class="shell" id="shell">
<aside class="side">
<div class="brand">Watchman</div>
<div class="nav-item off">数据源</div>
<div class="nav-item cur" id="nav-q">查询</div>
</aside>
<div class="main">
<header class="top">
<div class="crumb" id="crumb">Watchman / <b>查询</b></div>
<div class="who">当前角色 <span class="tag" id="who-role"></span></div>
</header>
<main class="content" id="view"></main>
<div class="pagefoot" id="pagefoot" hidden></div>
</div>
</div>
<div id="modal-root"></div>
<script>
(function () {
'use strict';
var ROLES = { admin: '管理者', handler: '处理者', viewer: '查看者' };
var SCREENS = [
['empty', '空列表'], ['list', '列表'], ['create', '新建草稿'], ['edit', '编辑草稿'], ['editoff', '编辑(已停用)'], ['version', '版本只读']
];
var RESULT_KINDS = [
['none', '未试跑'], ['running', '试跑中'], ['success', '成功'], ['empty', '空结果'], ['illegal_type', '非法类型'],
['failure', '失败'], ['disabled', '已停用'], ['circuit_open', '熔断中']
];
var FSUB = [['timeout', '超时'], ['connection', '连接失败'], ['syntax', 'SQL 语法错误']];
var TYPES = ['string', 'integer', 'number', 'boolean', 'datetime'];
var NOW = '2026-11-18 14:37';
// All sample data below is fictional. Hosts/datasources use reserved ".example.test" naming only.
var DS = [
{ id: 'ds1', name: '产线工艺库', on: true },
{ id: 'ds2', name: '设备台账库', on: true },
{ id: 'ds3', name: '质检结果库', on: true },
{ id: 'ds4', name: '历史归档库', on: false }
];
var SQL1 = 'SELECT lot_no, temperature, operator_name, measured_at\nFROM process_readings\nWHERE line_code = :line_code\n AND measured_at >= :since\n AND temperature >= :min_temp\nORDER BY measured_at DESC';
var SQL1_V2 = 'SELECT lot_no, temperature, measured_at\nFROM process_readings\nWHERE line_code = :line_code\n AND measured_at >= :since';
var SQL1_V1 = 'SELECT lot_no, temperature\nFROM process_readings\nWHERE line_code = :line_code';
var P_LINE = { name: 'line_code', type: 'string', req: true, def: '' };
var P_SINCE = { name: 'since', type: 'datetime', req: false, def: '2026-11-17 00:00:00' };
var P_MIN = { name: 'min_temp', type: 'number', req: false, def: '0' };
function clone(x) { return JSON.parse(JSON.stringify(x)); }
function ver(no, at, sql, params, outputs, idents, timeout, maxRows) {
return { no: no, at: at, by: 'admin.demo', sql: sql, params: clone(params), outputs: clone(outputs), idents: idents.slice(), timeout: timeout, maxRows: maxRows };
}
var QUERIES = [
{ id: 1, name: '产线温度采样', desc: '示例:按产线与时间窗取最近温度读数(虚构)', ds: 'ds1', on: true, updated: '2026-11-18 09:40',
sql: SQL1, params: [P_LINE, P_SINCE, P_MIN],
outputs: [{ name: 'lot_no', type: 'string' }, { name: 'temperature', type: 'number' }, { name: 'operator_name', type: 'string' }, { name: 'measured_at', type: 'datetime' }],
idents: ['process_readings', 'lot_no', 'temperature', 'operator_name', 'measured_at'], timeout: 5000, maxRows: 200, versions: [] },
{ id: 2, name: '设备停机记录', desc: '示例:按设备编码取停机事件(虚构)', ds: 'ds2', on: true, updated: '2026-11-17 16:05',
sql: 'SELECT equipment_code, stop_reason, stopped_at, duration_min\nFROM equipment_downtime\nWHERE equipment_code = :equipment_code\n AND stopped_at >= :since',
params: [{ name: 'equipment_code', type: 'string', req: true, def: '' }, P_SINCE],
outputs: [{ name: 'equipment_code', type: 'string' }, { name: 'stop_reason', type: 'string' }, { name: 'stopped_at', type: 'datetime' }, { name: 'duration_min', type: 'integer' }],
idents: ['equipment_downtime'], timeout: 3000, maxRows: 100, versions: [] },
{ id: 3, name: '质检不良统计', desc: '示例:按批次汇总不良代码,尚未发布(虚构)', ds: 'ds3', on: false, updated: '2026-11-16 11:22',
sql: 'SELECT defect_code, COUNT(*) AS cnt\nFROM qc_results\nWHERE batch_no = :batch_no\nGROUP BY defect_code',
params: [{ name: 'batch_no', type: 'string', req: true, def: '' }],
outputs: [{ name: 'defect_code', type: 'string' }, { name: 'cnt', type: 'integer' }],
idents: ['qc_results'], timeout: 5000, maxRows: 200, versions: [] },
{ id: 4, name: '在制批次清单', desc: '示例:当前在制批次(虚构)', ds: 'ds1', on: true, updated: '2026-11-15 08:50',
sql: 'SELECT lot_no, step_code, started_at\nFROM wip_lots\nWHERE line_code = :line_code',
params: [P_LINE],
outputs: [{ name: 'lot_no', type: 'string' }, { name: 'step_code', type: 'string' }, { name: 'started_at', type: 'datetime' }],
idents: ['wip_lots'], timeout: 5000, maxRows: 500, versions: [] }
];
(function seed() {
var q1 = QUERIES[0], q2 = QUERIES[1], q4 = QUERIES[3];
q1.versions = [
ver(3, '2026-11-18 09:40', SQL1, q1.params, q1.outputs, q1.idents, 5000, 200),
ver(2, '2026-11-14 15:20', SQL1_V2, [P_LINE, P_SINCE], [{ name: 'lot_no', type: 'string' }, { name: 'temperature', type: 'number' }, { name: 'measured_at', type: 'datetime' }], ['process_readings'], 5000, 100),
ver(1, '2026-11-10 10:02', SQL1_V1, [P_LINE], [{ name: 'lot_no', type: 'string' }, { name: 'temperature', type: 'number' }], ['process_readings'], 3000, 50)
];
q2.versions = [ver(1, '2026-11-17 16:05', q2.sql, q2.params, q2.outputs, q2.idents, 3000, 100)];
q4.versions = [
ver(2, '2026-11-15 08:50', q4.sql, q4.params, q4.outputs, q4.idents, 5000, 500),
ver(1, '2026-11-12 13:30', q4.sql, q4.params, q4.outputs.slice(0, 2), q4.idents, 5000, 200)
];
})();
var state = {
role: 'admin', screen: 'list', cur: 1, ver: 3, draft: null, pvals: {}, preview: null,
sim: 'success', fsub: 'timeout', flash: null, dirty: false, modal: false,
focusPreview: false, scrollPreview: false, refocus: null, timer: null, nextId: 5
};
function $(id) { return document.getElementById(id); }
function isAdmin() { return state.role === 'admin'; }
function esc(s) { return String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); }
function later(text) { return text + ' <span class="drop-later">正式版本进行删除</span>'; }
function qById(id) { for (var i = 0; i < QUERIES.length; i++) if (QUERIES[i].id === id) return QUERIES[i]; return QUERIES[0]; }
function curQ() { return qById(state.cur); }
function dsName(id) { for (var i = 0; i < DS.length; i++) if (DS[i].id === id) return DS[i].name; return '—'; }
function verOf(q, no) { for (var i = 0; i < q.versions.length; i++) if (q.versions[i].no === no) return q.versions[i]; return q.versions[0]; }
function latestNo(q) { return q.versions.length ? q.versions[0].no : 0; }
function isCreate() { return state.screen === 'create'; }
function isVersion() { return state.screen === 'version'; }
/* ---------- draft / preview params ---------- */
function blankDraft() {
return { name: '', desc: '', ds: 'ds1', sql: '', params: [], outputs: [], idents: [], timeout: 5000, maxRows: 200 };
}
function loadDraft(id) {
var q = qById(id);
state.draft = { name: q.name, desc: q.desc, ds: q.ds, sql: q.sql, params: clone(q.params), outputs: clone(q.outputs), idents: q.idents.slice(), timeout: q.timeout, maxRows: q.maxRows };
state.dirty = false;
}
function sourceParams() { return isVersion() ? verOf(curQ(), state.ver).params : state.draft.params; }
function initPvals() {
state.pvals = {};
sourceParams().forEach(function (p) { state.pvals[p.name] = p.def || ''; });
}
function setPath(path, val) {
var parts = path.split('.'), o = state, i;
for (i = 0; i < parts.length - 1; i++) o = o[parts[i]];
o[parts[parts.length - 1]] = val;
}
/* ---------- prototype toolbar ---------- */
function screenOn(id) {
var s = state.screen, q = qById(state.cur);
if (id === 'edit') return s === 'edit' && q.on;
if (id === 'editoff') return s === 'edit' && !q.on;
return s === id;
}
function renderProto() {
var r = '', s = '', k, b = '';
for (k in ROLES) r += '<button class="proto-btn' + (state.role === k ? ' on' : '') + '" data-role="' + k + '">' + ROLES[k] + '</button> ';
$('p-roles').innerHTML = r;
SCREENS.forEach(function (x) { s += '<button class="proto-btn' + (screenOn(x[0]) ? ' on' : '') + '" data-screen="' + x[0] + '">' + x[1] + '</button> '; });
$('p-screens').innerHTML = s;
RESULT_KINDS.forEach(function (x) { b += '<button class="proto-btn' + ((state.preview || 'none') === x[0] ? ' on' : '') + '" data-result="' + x[0] + '">' + x[1] + '</button> '; });
$('p-results').innerHTML = b;
var o = '';
FSUB.forEach(function (x) { o += '<option value="' + x[0] + '"' + (state.fsub === x[0] ? ' selected' : '') + '>' + x[1] + '</option>'; });
$('p-fsub').innerHTML = o;
$('who-role').textContent = ROLES[state.role];
$('nav-q').className = 'nav-item' + (isAdmin() ? ' cur' : ' off');
}
/* ---------- shared pieces ---------- */
function banner() {
return '<div class="local-banner">' + later('原型本地模拟:此页面不会向任何服务发送请求,「保存草稿」「发布」「试跑预览」等只会切换本页的演示状态。') + '</div>' +
(state.flash ? '<div class="flash ' + state.flash[0] + '">' + esc(state.flash[1]) + '</div>' : '');
}
function setCrumb(leaf) {
var html = 'Watchman / <b>查询</b>';
if (leaf) html += ' / <b>' + leaf + '</b>';
$('crumb').innerHTML = html;
}
function setFoot(actions) {
var foot = $('pagefoot');
foot.hidden = !actions;
foot.innerHTML = actions || '';
}
function statusCell(q) {
return q.on ? '<span class="status"><span class="dot"></span>启用</span>' : '<span class="status off"><span class="dot"></span>已停用</span>';
}
function verCell(q) { return q.versions.length ? 'v' + latestNo(q) : '<span class="hint">未发布</span>'; }
function listTable(rows) {
var h = '<div class="table-wrap"><table><thead><tr>' +
'<th>名称</th><th>数据源</th><th>状态</th><th>最新版本</th><th>更新时间</th><th>操作</th></tr></thead><tbody>';
rows.forEach(function (q) {
var dsOff = false;
h += '<tr class="' + (q.on ? '' : 'off') + '"><td>' + esc(q.name) + '</td><td>' + esc(dsName(q.ds)) + '</td><td>' + statusCell(q) +
'</td><td class="mono">' + verCell(q) + '</td><td class="mono">' + q.updated + '</td><td class="ops">' +
'<button class="btn link" data-act="open" data-id="' + q.id + '">打开</button>' +
'<button class="btn link"' + (q.on && !dsOff ? ' data-act="preview" data-id="' + q.id + '"' : ' disabled title="已停用,不能预览"') + '>预览</button>' +
'</td></tr>';
});
return h + '</tbody></table></div>';
}
/* ---------- schema editors ---------- */
function typeSelect(path, val, ro) {
var h = '<select data-bind="' + path + '"' + (ro ? ' disabled' : '') + '>';
TYPES.forEach(function (t) { h += '<option' + (t === val ? ' selected' : '') + '>' + t + '</option>'; });
return h + '</select>';
}
function paramsEditor(ps, ro) {
var h = '';
if (!ro) h += '<div class="tbl-tools"><button class="btn sm" data-act="add-param">添加参数</button></div>';
if (!ps.length) return h + '<div class="empty sm"><p>尚未声明参数。SQL 中的 :name 必须在此声明,未声明的参数会被拒绝。</p></div>';
h += '<div class="table-wrap inner"><table><thead><tr><th>参数名</th><th>类型</th><th>必填</th><th>默认值</th>' + (ro ? '' : '<th>操作</th>') + '</tr></thead><tbody>';
ps.forEach(function (p, i) {
var b = 'draft.params.' + i;
if (ro) {
h += '<tr><td class="mono">' + esc(p.name) + '</td><td class="mono">' + p.type + '</td><td>' + (p.req ? '是' : '否') + '</td><td class="mono">' + (p.def === '' ? '<span class="hint">—</span>' : esc(p.def)) + '</td></tr>';
} else {
h += '<tr><td><input type="text" class="mono" data-bind="' + b + '.name" value="' + esc(p.name) + '" placeholder="例如 line_code"></td>' +
'<td>' + typeSelect(b + '.type', p.type) + '</td>' +
'<td><input type="checkbox" data-bind="' + b + '.req"' + (p.req ? ' checked' : '') + '></td>' +
'<td><input type="text" data-bind="' + b + '.def" value="' + esc(p.def) + '" placeholder="可空"></td>' +
'<td class="ops"><button class="btn link danger" data-act="del-param" data-i="' + i + '">删除</button></td></tr>';
}
});
return h + '</tbody></table></div>';
}
function outputsEditor(os, ro) {
var h = '';
if (!ro) h += '<div class="tbl-tools"><button class="btn sm" data-act="add-out">添加输出字段</button></div>';
if (!os.length) return h + '<div class="empty sm"><p>尚未声明输出字段。输出契约用于检查结果类型。</p></div>';
h += '<div class="table-wrap inner"><table><thead><tr><th>字段名</th><th>类型</th>' + (ro ? '' : '<th>操作</th>') + '</tr></thead><tbody>';
os.forEach(function (o, i) {
var b = 'draft.outputs.' + i;
if (ro) h += '<tr><td class="mono">' + esc(o.name) + '</td><td class="mono">' + o.type + '</td></tr>';
else h += '<tr><td><input type="text" class="mono" data-bind="' + b + '.name" value="' + esc(o.name) + '" placeholder="例如 lot_no"></td>' +
'<td>' + typeSelect(b + '.type', o.type) + '</td>' +
'<td class="ops"><button class="btn link danger" data-act="del-out" data-i="' + i + '">删除</button></td></tr>';
});
return h + '</tbody></table></div>';
}
function identsBlock(ids, ro) {
var h = '<div class="chips">';
if (!ids.length) h += '<span class="hint">无(不允许动态标识符)</span>';
ids.forEach(function (t, i) {
h += '<span class="chip">' + esc(t) + (ro ? '' : '<button title="移除" data-act="del-ident" data-i="' + i + '">×</button>') + '</span>';
});
h += '</div>';
if (!ro) h += '<div class="ident-add"><input type="text" id="f-ident-input" placeholder="输入标识符后按回车,例如 process_readings"><button class="btn" data-act="add-ident">添加</button></div>';
h += '<div class="hint" style="margin-top:6px">' + later('标识符(表/字段名)不能作为绑定参数的值;只有这里声明的名称允许出现在 SQL 的标识符位置,留空即不允许。占位语法待维护者确认。') + '</div>';
return h;
}
/* ---------- SQL chips (live) ---------- */
function detectParams(sql) {
var out = [], re = /(^|[^:\w]):([A-Za-z_]\w*)/g, m;
while ((m = re.exec(sql || ''))) if (out.indexOf(m[2]) < 0) out.push(m[2]);
return out;
}
function chipsHtml(sql, params) {
var used = detectParams(sql), declared = params.map(function (p) { return p.name; }), h = '';
if (!used.length) return '<span class="hint">SQL 中尚未使用 :参数。</span>';
h += '<span class="hint">SQL 中的参数:</span>';
used.forEach(function (n) {
h += declared.indexOf(n) >= 0 ? '<span class="chip ok">:' + esc(n) + '</span>' : '<span class="chip bad" title="未在参数 schema 中声明,保存会被拒绝">:' + esc(n) + ' 未声明</span>';
});
declared.forEach(function (n) { if (n && used.indexOf(n) < 0) h += '<span class="chip dim" title="已声明但 SQL 中未使用">' + esc(n) + ' 未使用</span>'; });
return h;
}
function refreshChips() {
var el = $('sql-chips');
if (el && state.draft) el.innerHTML = chipsHtml(state.draft.sql, state.draft.params);
}
/* ---------- preview ---------- */
function pvInputs(ps) {
if (!ps.length) return '<div class="hint" style="margin-bottom:12px">该查询没有声明参数,可直接试跑。</div>';
var h = '<div class="pv-grid">';
ps.forEach(function (p) {
var v = state.pvals[p.name] == null ? '' : state.pvals[p.name], inp;
if (p.type === 'boolean') {
inp = '<select data-bind="pvals.' + p.name + '"><option value=""' + (v === '' ? ' selected' : '') + '>(未填)</option><option value="true"' + (v === 'true' ? ' selected' : '') + '>true</option><option value="false"' + (v === 'false' ? ' selected' : '') + '>false</option></select>';
} else {
inp = '<input type="' + (p.type === 'integer' || p.type === 'number' ? 'number' : 'text') + '" data-bind="pvals.' + p.name + '" value="' + esc(v) + '" placeholder="' + (p.type === 'datetime' ? 'YYYY-MM-DD HH:MM:SS' : '') + '">';
}
h += '<div class="field"><label><span class="mono">' + esc(p.name) + '</span> · ' + p.type + (p.req ? '<span class="req">*</span>' : '') + '</label>' + inp + '</div>';
});
return h + '</div>';
}
function refreshPvParams() {
var el = $('pv-params');
if (el) el.innerHTML = pvInputs(sourceParams());
}
function maskCol(n) { return /operator|person|user/i.test(n); }
function sampleVal(o, i) {
if (maskCol(o.name)) return '张**';
if (o.type === 'integer') return String(i * 3 + 2);
if (o.type === 'number') return (71.2 + i * 0.8).toFixed(1);
if (o.type === 'boolean') return i % 2 ? 'true' : 'false';
if (o.type === 'datetime') return '2026-11-18 08:' + (10 + i * 5) + ':00';
return o.name === 'lot_no' ? 'LOT-100' + i : o.name + '-' + i;
}
function successTable(outs) {
var h = '<div class="table-wrap r-table"><table><thead><tr>';
outs.forEach(function (o) { h += '<th>' + esc(o.name) + (maskCol(o.name) ? ' <span class="tag warn">脱敏</span>' : '') + '</th>'; });
h += '</tr></thead><tbody>';
for (var i = 1; i <= 3; i++) {
h += '<tr>';
outs.forEach(function (o) { h += '<td class="mono">' + esc(sampleVal(o, i)) + '</td>'; });
h += '</tr>';
}
return h + '</tbody></table></div>';
}
function contextInfo() {
var q = curQ();
if (isVersion()) { var v = verOf(q, state.ver); return { outs: v.outputs, timeout: v.timeout, maxRows: v.maxRows, dsId: q.ds, label: '版本 v' + v.no + '(已冻结)' }; }
var d = isCreate() ? state.draft : q; return { outs: d.outputs, timeout: d.timeout, maxRows: d.maxRows, dsId: d.ds, label: '草稿(已保存内容)' };
}
function resultPanel(kind) {
var q = curQ(), c = contextInfo(), dsn = dsName(c.dsId);
var limits = 'timeout_ms=' + c.timeout + ' · max_rows=' + c.maxRows;
var foot = '仅预览:不创建报警、不发送通知、不进入正式运行';
if (kind === 'running') {
return '<div class="result pend"><div class="r-title"><span class="spin"></span>试跑中</div><div class="r-body">' + later('正在试跑「' + esc(q.name) + '」(本地模拟,未发出任何请求)…') + '</div></div>';
}
if (kind === 'success') {
return '<div class="result ok"><div class="r-title">试跑成功</div><div class="r-body">返回 3 行样例,列符合输出契约。标记「脱敏」的列按简单策略遮盖。</div>' +
successTable(c.outs) +
'<div class="r-meta">' + later('耗时示意 0.32 秒(虚构) · ' + limits + ' · 数据源 ' + esc(dsn)) + '<br>' + foot + '</div></div>';
}
if (kind === 'empty') {
return '<div class="result grey"><div class="r-title">空结果</div><div class="r-body">查询已成功执行,但没有符合条件的行。这不是失败,也不是类型错误。</div>' +
'<div class="r-meta">' + later('耗时示意 0.18 秒(虚构) · ' + limits) + '<br>' + foot + '</div></div>';
}
if (kind === 'illegal_type') {
var col = null, i;
for (i = 0; i < c.outs.length; i++) if (c.outs[i].type !== 'string') { col = c.outs[i]; break; }
if (!col) col = c.outs[0] || { name: 'value', type: 'integer' };
var exp = col.type === 'string' ? 'integer' : col.type;
return '<div class="result warn"><div class="r-title">输出类型不匹配</div><div class="r-body">查询已执行,但返回值与输出契约不符,整批结果不视为合法输出。</div>' +
'<div class="table-wrap r-table"><table><thead><tr><th>行</th><th>字段</th><th>契约类型</th><th>实际值(样例)</th></tr></thead><tbody>' +
'<tr><td class="mono">2</td><td class="mono">' + esc(col.name) + '</td><td class="mono">' + exp + '</td><td class="mono">"N/A"(字符串)</td></tr>' +
'<tr><td class="mono">5</td><td class="mono">' + esc(col.name) + '</td><td class="mono">' + exp + '</td><td class="mono">"--"(字符串)</td></tr>' +
'</tbody></table></div>' +
'<div class="r-meta">' + later('共 2 处不匹配(虚构) · ' + limits) + '<br>' + foot + '</div></div>';
}
if (kind === 'failure') {
var f = {
timeout: ['执行超时', '超过 timeout_ms=' + c.timeout + ' 仍未返回,已中止查询。可缩小时间窗或调整限制后重试。', '超时不是 SQL 语法错误,也不是类型不匹配'],
connection: ['连接失败', '无法连接到数据源「' + dsn + '」。', '连接类失败会计入该数据源的熔断统计(与 M03 一致)'],
syntax: ['SQL 语法错误', '源库拒绝了该 SQL:near "FORM"(虚构示例)。请检查 SQL 模板。', '语法错误不属于连接失败,不计入熔断统计']
}[state.fsub];
return '<div class="result bad"><div class="r-title">试跑失败 · ' + f[0] + '</div><div class="r-body">' + esc(f[1]) + '</div>' +
'<div class="r-meta">' + later(f[2] + ' · ' + limits) + '<br>' + foot + '</div></div>';
}
if (kind === 'disabled') {
var body = !q.on ? '查询「' + q.name + '」已停用,不能试跑。请先在页脚「启用」。' : '所绑定的数据源「' + dsn + '」已停用,不能试跑。';
return '<div class="result warn"><div class="r-title">已停用,未执行</div><div class="r-body">' + esc(body) + '</div>' +
'<div class="r-meta">' + later('被拒绝时不会向源库发起任何查询。') + '</div></div>';
}
if (kind === 'circuit_open') {
return '<div class="result bad"><div class="r-title">数据源熔断中,未执行</div><div class="r-body">数据源「' + esc(dsn) + '」当前熔断开闸,不会向源库发起查询。预计恢复时间 2026-11-18 15:10(示意)。</div>' +
'<div class="r-meta">' + later('熔断由数据源侧连续失败触发;此处不绕过熔断。') + '</div></div>';
}
return '<div class="note">' + later('尚未试跑。填写参数后点击页脚「试跑预览」可演示结果(本地模拟)。') + '</div>';
}
function previewCard() {
var ver_ = isVersion(), c = contextInfo();
var h = '<div class="card' + (state.focusPreview ? ' focus' : '') + '" id="pv-card"><h3>试跑预览<span class="sub">仅返回样例,不进入报警</span></h3>';
h += '<div class="pv-target">预览对象:<b>' + c.label + '</b>' + (ver_ ? '' : '') + '</div>';
if (!ver_) h += '<div class="note warn" id="pv-dirty" style="margin-bottom:10px"' + (state.dirty ? '' : ' hidden') + '>' + later('当前有未保存修改;预览使用已保存的草稿,不含这些修改(待确认)。') + '</div>';
h += '<div id="pv-params">' + pvInputs(sourceParams()) + '</div>';
h += '<div id="pv-result">' + resultPanel(state.preview || 'none') + '</div>';
return h + '</div>';
}
/* ---------- versions ---------- */
function versionsCard(q, hlNo) {
var h = '<div class="card"><h3>版本<span class="sub">仅已发布版本;发布请使用页脚「发布」</span></h3>';
if (isCreate()) return h + '<div class="empty sm"><p>保存草稿并发布后,版本会出现在这里。</p></div></div>';
if (!q.versions.length) return h + '<div class="empty sm"><p>尚未发布。发布后会生成 v1,且内容不可再改。</p></div></div>';
h += '<div class="table-wrap"><table><thead><tr><th>版本</th><th>发布时间</th><th>发布人</th><th>数据库限制</th><th>操作</th></tr></thead><tbody>';
q.versions.forEach(function (v, idx) {
h += '<tr class="' + (v.no === hlNo ? 'hl' : '') + '"><td class="mono">v' + v.no + (idx === 0 ? ' <span class="tag ok">最新</span>' : '') + '</td><td class="mono">' + v.at + '</td><td class="mono">' + v.by +
'</td><td class="mono">timeout ' + v.timeout + ' / rows ' + v.maxRows + '</td><td class="ops"><button class="btn link" data-act="openver" data-no="' + v.no + '">打开</button></td></tr>';
});
return h + '</tbody></table></div></div>';
}
/* ---------- footers ---------- */
function footEdit() {
var q = curQ(), create = isCreate(), h = '';
h += '<button class="btn" data-act="list">返回列表</button>';
h += '<button class="btn primary" data-act="save">保存草稿</button>';
h += create ? '<button class="btn" disabled title="请先保存草稿">发布</button>' : '<button class="btn outline" data-act="publish">发布</button>';
if (!create) h += q.on ? '<button class="btn danger" data-act="toggle">停用</button>' : '<button class="btn" data-act="toggle">启用</button>';
h += create ? '<button class="btn" disabled title="请先保存草稿">试跑预览</button>' : '<button class="btn" data-act="run"' + (state.preview === 'running' ? ' disabled' : '') + '>试跑预览</button>';
return h;
}
function footVersion() {
return '<button class="btn" data-act="list">返回列表</button><button class="btn" data-act="draft">返回草稿</button>' +
'<button class="btn" data-act="run"' + (state.preview === 'running' ? ' disabled' : '') + '>试跑预览</button>';
}
/* ---------- screens ---------- */
function vDenied() {
setCrumb(''); setFoot('');
return banner() + '<div class="empty"><h3>无法进入查询</h3><p>只有管理者可以进入查询界面。</p>' +
'<p class="hint" style="margin:0">' + later('后端返回 42000,并带缺失的权限点 perm:data:emp:watchman.query.read。') + '</p></div>';
}
function vEmpty() {
setCrumb(''); setFoot('');
return banner() + '<div class="list-actions"><button class="btn primary" data-act="create">新建</button></div>' +
'<div class="empty"><h3>还没有查询</h3><p>管理者可以新建第一个查询定义:选择数据源,写参数化 SQL,声明参数与输出契约。</p></div>';
}
function vList() {
setCrumb(''); setFoot('');
return banner() + '<div class="list-actions"><button class="btn primary" data-act="create">新建</button></div>' + listTable(QUERIES) +
'<p class="hint" style="margin-top:10px">' + later('已停用的行保持可见,「预览」置灰;「打开」进入草稿详情。分页/筛选未在需求中确认,原型未做。') + '</p>';
}
function basicCard() {
var d = state.draft, q = curQ(), create = isCreate(), dsOpts = '';
DS.forEach(function (x) {
dsOpts += '<option value="' + x.id + '"' + (d.ds === x.id ? ' selected' : '') + (x.on ? '' : ' disabled') + '>' + x.name + (x.on ? '' : '(已停用)') + '</option>';
});
var st = create ? '<span class="hint">新建后默认启用</span>' : statusCell(q) + ' <span class="hint">· 通过页脚「' + (q.on ? '停用' : '启用') + '」切换</span>';
return '<div class="card"><h3>基本信息' + (create ? '<span class="sub">草稿</span>' : '<span class="sub">草稿 · 最新已发布 ' + (q.versions.length ? 'v' + latestNo(q) : '无') + '</span>') + '</h3>' +
'<div class="form-grid">' +
'<div class="field"><label>名称<span class="req">*</span></label><input type="text" data-bind="draft.name" value="' + esc(d.name) + '" placeholder="租户内唯一"></div>' +
'<div class="field"><label>数据源<span class="req">*</span></label><select data-bind="draft.ds">' + dsOpts + '</select>' +
'<span class="hint">' + later('仅可选择可用的数据库数据源;已停用的灰显不可选。') + '</span></div>' +
'<div class="field full"><label>用途说明</label><textarea rows="2" data-bind="draft.desc">' + esc(d.desc) + '</textarea></div>' +
'<div class="field"><label>状态</label><div>' + st + '</div></div>' +
'</div></div>';
}
function sqlCard() {
var d = state.draft;
return '<div class="card"><h3>SQL 模板</h3>' +
'<div class="field"><textarea class="sql" rows="8" data-bind="draft.sql" spellcheck="false" placeholder="SELECT lot_no FROM process_readings WHERE line_code = :line_code">' + esc(d.sql) + '</textarea>' +
'<span class="hint">' + later('使用命名参数,例如 :line_code,值一律参数绑定,不拼接进 SQL。不靠 SELECT 前缀判定安全,是否只读由数据源账户与执行器保证。') + '</span></div>' +
'<div class="chips" id="sql-chips">' + chipsHtml(d.sql, d.params) + '</div></div>';
}
function limitsCard() {
var d = state.draft;
return '<div class="card"><h3>执行限制</h3><div class="form-grid">' +
'<div class="field"><label>timeout_ms<span class="req">*</span></label><input type="number" data-bind="draft.timeout" value="' + esc(d.timeout) + '"></div>' +
'<div class="field"><label>max_rows<span class="req">*</span></label><input type="number" data-bind="draft.maxRows" value="' + esc(d.maxRows) + '"></div>' +
'<div class="field full"><span class="hint">' + later('服务端有上限封顶(示意:timeout_ms ≤ 30000,max_rows ≤ 1000,具体值以后端为准),表单填过大会被拒绝。') + '</span></div>' +
'</div></div>';
}
function vEdit() {
var create = isCreate(), q = curQ(), d = state.draft;
setCrumb(create ? '新建' : '详情');
setFoot(footEdit());
var h = banner();
if (!create && !q.on) h += '<div class="note warn" style="margin-bottom:14px">该查询已停用。仍可查看与编辑草稿,但不能试跑预览;可在页脚「启用」。</div>';
h += basicCard() + sqlCard();
h += '<div class="card"><h3>参数 schema<span class="sub">命名参数 · 未知参数拒绝</span></h3>' + paramsEditor(d.params, false) + '</div>';
h += '<div class="card"><h3>输出 schema<span class="sub">输出契约 · 用于检查结果类型</span></h3>' + outputsEditor(d.outputs, false) + '</div>';
h += '<div class="card"><h3>允许的标识符</h3>' + identsBlock(d.idents, false) + '</div>';
h += limitsCard();
h += previewCard();
h += versionsCard(q, 0);
h += '<div class="card"><h3>引用<span class="sub">场景尚未落地</span></h3><div class="empty sm"><p>尚无引用</p></div></div>';
return h;
}
function vVersion() {
var q = curQ(), v = verOf(q, state.ver);
setCrumb('详情 / 版本 v' + v.no);
setFoot(footVersion());
var h = banner();
h += '<div class="note" style="margin-bottom:14px">版本 v' + v.no + ' 已冻结,内容不可修改。更正需回到草稿修改后发布新版本;这里仍可试跑预览。</div>';
h += '<div class="card"><h3>版本信息<span class="sub"><span class="tag grey">只读</span></span></h3><dl class="kv">' +
'<dt>查询</dt><dd>' + esc(q.name) + '</dd><dt>版本</dt><dd class="mono">v' + v.no + (v.no === latestNo(q) ? ' <span class="tag ok">最新</span>' : '') + '</dd>' +
'<dt>发布时间</dt><dd class="mono">' + v.at + '</dd><dt>发布人</dt><dd class="mono">' + v.by + '</dd><dt>数据源</dt><dd>' + esc(dsName(q.ds)) + '</dd></dl></div>';
h += '<div class="card"><h3>SQL 模板<span class="sub">冻结</span></h3><pre class="sql">' + esc(v.sql) + '</pre></div>';
h += '<div class="card"><h3>参数 schema<span class="sub">冻结</span></h3>' + paramsEditor(v.params, true) + '</div>';
h += '<div class="card"><h3>输出 schema<span class="sub">冻结</span></h3>' + outputsEditor(v.outputs, true) + '</div>';
h += '<div class="card"><h3>允许的标识符<span class="sub">冻结</span></h3>' + identsBlock(v.idents, true) + '</div>';
h += '<div class="card"><h3>执行限制<span class="sub">冻结</span></h3><dl class="kv"><dt>timeout_ms</dt><dd class="mono">' + v.timeout + '</dd><dt>max_rows</dt><dd class="mono">' + v.maxRows + '</dd></dl></div>';
h += previewCard();
h += versionsCard(q, v.no);
return h;
}
/* ---------- modal ---------- */
function renderModal() {
var root = $('modal-root');
if (!state.modal) { root.innerHTML = ''; return; }
var q = curQ(), next = latestNo(q) + 1;
root.innerHTML = '<div class="modal-mask"><div class="modal"><h3>确认发布 v' + next + '?</h3>' +
'<p>将把当前已保存的草稿固化为不可变版本 v' + next + '。发布后不能修改或删除,更正需发布新版本。</p>' +
'<div class="row"><button class="btn" data-act="cancel-pub">取消</button><button class="btn primary" data-act="confirm-pub">确认发布</button></div>' +
'<p class="hint" style="margin:10px 0 0">' + later('未来用 ElMessageBox 确认。') + '</p></div></div>';
}
/* ---------- render / navigation ---------- */
function render(resetScroll) {
renderProto();
var view = $('view'), st = view.scrollTop, s = state.screen, h;
if (!isAdmin()) h = vDenied();
else if (s === 'empty') h = vEmpty();
else if (s === 'list') h = vList();
else if (s === 'create' || s === 'edit') h = vEdit();
else if (s === 'version') h = vVersion();
else h = vList();
view.innerHTML = h;
renderModal();
sizeShell();
view.scrollTop = resetScroll ? 0 : st;
if (state.scrollPreview || state.focusPreview) {
var pc = $('pv-card');
if (pc) pc.scrollIntoView({ block: state.focusPreview ? 'start' : 'nearest' });
state.scrollPreview = false;
}
if (state.refocus) { var f = $(state.refocus); if (f) f.focus(); state.refocus = null; }
}
function sizeShell() {
$('shell').style.setProperty('height', 'calc(100vh - ' + $('proto').offsetHeight + 'px)');
}
function clearTimer() { if (state.timer) { clearTimeout(state.timer); state.timer = null; } }
function go(screen, flash) {
clearTimer();
state.screen = screen;
state.flash = flash || null;
state.preview = null;
state.modal = false;
if (screen === 'create') { state.draft = blankDraft(); state.dirty = false; initPvals(); }
else if (screen === 'edit') { loadDraft(state.cur); initPvals(); }
else if (screen === 'version') { initPvals(); }
render(true);
}
function setFlash(cls, text, keepScroll) { state.flash = [cls, text]; render(!keepScroll); }
/* ---------- actions ---------- */
function validate() {
var d = state.draft, i, names = [];
if (!String(d.name).trim()) return '名称必填。';
for (i = 0; i < QUERIES.length; i++) if (QUERIES[i].name === d.name.trim() && (isCreate() || QUERIES[i].id !== state.cur)) return '租户内名称已存在:' + d.name.trim() + '。';
if (!String(d.sql).trim()) return 'SQL 模板必填。';
for (i = 0; i < d.params.length; i++) {
var n = d.params[i].name;
if (!/^[A-Za-z_]\w*$/.test(n)) return '参数名不合法:' + (n || '(空)') + '。';
if (names.indexOf(n) >= 0) return '参数名重复:' + n + '。';
names.push(n);
}
var used = detectParams(d.sql);
for (i = 0; i < used.length; i++) if (names.indexOf(used[i]) < 0) return 'SQL 含未声明参数 :' + used[i] + ',未知参数会被拒绝。';
for (i = 0; i < d.outputs.length; i++) if (!/^[A-Za-z_]\w*$/.test(d.outputs[i].name)) return '输出字段名不合法:' + (d.outputs[i].name || '(空)') + '。';
var t = Number(d.timeout), r = Number(d.maxRows);
if (!(t >= 1 && t <= 30000)) return 'timeout_ms 需在 1~30000 之间(示意上限)。';
if (!(r >= 1 && r <= 1000)) return 'max_rows 需在 1~1000 之间(示意上限)。';
return null;
}
function doSave() {
var err = validate();
if (err) { setFlash('bad', '无法保存:' + err); return; }
var d = state.draft, q;
if (isCreate()) {
q = { id: state.nextId++, versions: [], on: true };
QUERIES.push(q);
state.cur = q.id;
} else q = curQ();
q.name = d.name.trim(); q.desc = d.desc; q.ds = d.ds; q.sql = d.sql;
q.params = clone(d.params); q.outputs = clone(d.outputs); q.idents = d.idents.slice();
q.timeout = Number(d.timeout); q.maxRows = Number(d.maxRows); q.updated = NOW;
if (state.screen === 'create') { go('edit', ['ok', '草稿已保存(本地模拟)。']); return; }
loadDraft(q.id);
setFlash('ok', '草稿已保存(本地模拟)。');
}
function doPublish() {
if (state.dirty) { setFlash('warn', '有未保存修改,请先保存草稿再发布。'); return; }
var q = curQ();
if (!q.sql || !q.sql.trim()) { setFlash('bad', '无法发布:草稿 SQL 为空。'); return; }
state.modal = true; renderModal();
}
function confirmPublish() {
var q = curQ(), no = latestNo(q) + 1;
q.versions.unshift(ver(no, NOW, q.sql, q.params, q.outputs, q.idents, q.timeout, q.maxRows));
q.updated = NOW;
state.modal = false;
setFlash('ok', '已发布 v' + no + '(本地模拟)。版本内容已冻结,继续修改草稿不影响它。');
}
function runPreview() {
clearTimer();
state.preview = 'running'; state.scrollPreview = true; render();
state.timer = setTimeout(function () {
state.timer = null; state.preview = !curQ().on ? 'disabled' : state.sim; state.scrollPreview = true; render();
}, 1000);
}
function pickResult(kind) {
clearTimer();
if (kind !== 'none' && kind !== 'running') state.sim = kind;
if (state.screen !== 'edit' && state.screen !== 'version') {
if (!isAdmin()) { render(); return; }
state.cur = state.cur || 1; go('edit');
}
state.preview = kind === 'none' ? null : kind;
state.scrollPreview = true; render();
}
/* ---------- events ---------- */
document.addEventListener('click', function (e) {
var t = e.target.closest('button');
if (!t || t.disabled) return;
if (t.hasAttribute('data-role')) { state.role = t.getAttribute('data-role'); render(); return; }
if (t.hasAttribute('data-screen')) {
var sc = t.getAttribute('data-screen');
if (sc === 'edit') { state.cur = state.cur === 3 ? 1 : state.cur; go('edit'); }
else if (sc === 'editoff') { state.cur = 3; go('edit'); }
else if (sc === 'version') { state.cur = state.cur === 3 ? 1 : state.cur; state.ver = latestNo(curQ()); go('version'); }
else go(sc);
return;
}
if (t.hasAttribute('data-result')) { pickResult(t.getAttribute('data-result')); return; }
var act = t.getAttribute('data-act');
if (!act) return;
var i = +t.getAttribute('data-i'), d = state.draft;
switch (act) {
case 'list': go('list'); break;
case 'create': go('create'); break;
case 'open': state.cur = +t.getAttribute('data-id'); go('edit'); break;
case 'preview': state.cur = +t.getAttribute('data-id'); state.focusPreview = true; go('edit'); state.focusPreview = false; break;
case 'draft': go('edit'); break;
case 'openver': state.ver = +t.getAttribute('data-no'); go('version'); break;
case 'save': doSave(); break;
case 'publish': doPublish(); break;
case 'confirm-pub': confirmPublish(); break;
case 'cancel-pub': state.modal = false; renderModal(); break;
case 'toggle': var q = curQ(); q.on = !q.on; q.updated = NOW; state.preview = null; setFlash('ok', q.on ? '已启用(本地模拟)。' : '已停用(本地模拟)。已发布版本不受影响。'); break;
case 'run': runPreview(); break;
case 'add-param': d.params.push({ name: '', type: 'string', req: false, def: '' }); state.dirty = true; render(); break;
case 'del-param': d.params.splice(i, 1); state.dirty = true; initPvalsKeep(); render(); break;
case 'add-out': d.outputs.push({ name: '', type: 'string' }); state.dirty = true; render(); break;
case 'del-out': d.outputs.splice(i, 1); state.dirty = true; render(); break;
case 'del-ident': d.idents.splice(i, 1); state.dirty = true; render(); break;
case 'add-ident': addIdent(); break;
}
});
function initPvalsKeep() {
var old = state.pvals; state.pvals = {};
sourceParams().forEach(function (p) { state.pvals[p.name] = old[p.name] != null ? old[p.name] : (p.def || ''); });
}
function addIdent() {
var el = $('f-ident-input'), v = el ? el.value.trim() : '';
if (!v) return;
if (!/^[A-Za-z_][\w.]*$/.test(v)) { state.refocus = 'f-ident-input'; setFlash('warn', '标识符只能包含字母、数字、下划线和点:' + v, true); return; }
if (state.draft.idents.indexOf(v) < 0) state.draft.idents.push(v);
state.dirty = true; state.refocus = 'f-ident-input'; render();
}
function onBind(e) {
var el = e.target, path = el.getAttribute && el.getAttribute('data-bind');
if (!path) return;
var val = el.type === 'checkbox' ? el.checked : el.value;
setPath(path, val);
if (path.indexOf('draft.') === 0) {
state.dirty = true;
var pd = $('pv-dirty'); if (pd) pd.hidden = false;
if (path === 'draft.sql' || /^draft\.params\./.test(path)) refreshChips();
if (e.type === 'change' && /^draft\.params\./.test(path)) { initPvalsKeep(); refreshPvParams(); }
}
}
document.addEventListener('input', onBind);
document.addEventListener('change', function (e) {
if (e.target.id === 'p-fsub') { state.fsub = e.target.value; if (state.preview === 'failure') render(); return; }
onBind(e);
});
document.addEventListener('keydown', function (e) {
if (e.key === 'Enter' && e.target.id === 'f-ident-input') { e.preventDefault(); addIdent(); }
});
window.addEventListener('resize', sizeShell);
render(true);
})();
</script>
</body>
</html>
+105
View File
@@ -0,0 +1,105 @@
# M04 查询定义与采集 Requirement
## Goal
维护者能在控制台维护受控查询草稿(参数化 SQL、参数 schema、输出契约、执行限制),发布不可变版本,并对草稿或已发布版本做只读预览试跑。预览区分空结果、非法类型与执行失败;不进入报警/通知,也不承担场景定时采集。
## Background
- 模块:`docs/tasks/INDEX.md` M04;覆盖旧细项 A-016~A-020;需求 A-02。
- 前置:M03 DONE_LOCAL。数据源 usable/熔断见 D23;查询执行必须调用 `assert_usable` 与失败记账入口。
- 决策:D14 RLS;D19 三角色;D22 按钮/密码框约定;**D24** 本模块口径(参数化 SQL + 不可变版本 + 预览边界)。
- 门禁:`gatePolicy.selected=autonomous`;Vue 前 HTML 原型确认。
## In Scope
- `query_definitions`:租户内名称唯一;绑定可用数据库数据源;草稿 SQL/参数 schema/输出契约/限制;启停。
- `query_versions`:`publish` 从当前草稿拷贝不可变快照;`(definition_id, version_no)` 唯一;内容禁止改写/删除字段更新。
- 参数:命名参数绑定;未知参数拒绝;类型/必填/默认值校验。
- 标识符:不可作绑定值的表/字段等仅允许白名单(本阶段可先支持固定占位语法或显式允许列表字段,禁止任意拼接)。
- 只读执行器:超时、最大行数;不靠 `SELECT` 前缀判定安全;平台库事务与源库查询分离。
- 预览 API/UI:草稿预览与指定版本预览;空/非法类型/失败三分;样例脱敏;不写正式报警。
- 权限:仅 admin 的 read/write/publish/preview。
- 引用:查询定义/版本 references 返回空列表+稳定占位;数据源 references 可列出引用它的查询(只读提示)。
- 控制台:列表、编辑草稿、发布、版本只读、试跑预览;布局遵守 D22/`docs/current/frontend-ui.md`。
- 审计:创建、更新草稿、启停、发布、预览(预览审计不含结果全文/秘密)。
## Out Of Scope
- 结构化表/字段选择器(非参数化 SQL)。
- 任意脚本、eval、动态拼 SQL 条件串。
- 字段映射、规则判定、报警、企微、场景 Cron 正式采集(M05/M06/M07/M08)。
- 非数据库数据源执行。
- 绕过熔断直连源库。
- 真实 MES/生产库写入;口令或预览全文入库外日志/仓库。
- 查询物理删除(本阶段停用即可)。
## Required Behavior
- 有权限用户可 CRUD 草稿;停用后仍可查看,不可预览执行(或明确拒绝并提示);可再启用。
- `publish` 生成递增 `version_no`;历史版本只读;草稿可继续改,不影响已发布快照。
- 预览前 `assert_usable(datasource)`;源停用或熔断开闸则拒绝预览并记账策略与 M03 业务失败一致(连接类失败计入熔断)。
- 参数含 SQL 片段时仍参数绑定,不形成结构注入。
- 多行/多对象结果可返回;不在本模块串联报警。
- 空结果、输出契约类型不匹配、超时/连接/语法类失败分开展示。
- 跨租户不可见。无会话 41000;非 admin 42000 且带权限点。
## User Flow
1. 管理者打开查询列表。
2. 新建:选数据源、用途、SQL 模板、参数与输出契约、限制 → 保存草稿。
3. 可对草稿试跑预览(填参数)。
4. 发布 → 生成版本;可查看版本列表与只读详情;可对版本试跑。
5. 继续改草稿不影响已发布版本;再次发布得到新版本号。
6. 停用定义后不可作为后续场景候选(约定字段/列表过滤);本阶段场景未落地,提供稳定 `enabled` 语义即可。
## Business Rules
- 租户内 `name` 唯一。无物理删除。
- 版本内容不可变;更正靠新版本。
- 预览不创建报警、不发送通知、不推进正式 run 业务状态机(若写 run_records 须明确 `sample`/试跑标记且默认不做;本轮预览结果仅 API 响应)。
- 最新已发布版本号可空(从未发布)。
- 数据源被引用时,数据源 references 返回查询条目;查询侧 references 仍可空(场景未到)。
## Data Rules
- 租户服务端注入;表启用 RLS。
- SQL/参数/输出/限制可回显给有权限用户;源库口令永不回显。
- 预览响应可含样例行,敏感列按输出契约或简单脱敏策略处理;日志不得落完整结果集或口令。
## API Contract(摘要)
- `GET/POST /queries`,`GET/PATCH /queries/{id}`,`POST .../enable|disable`,`POST .../publish`
- `GET /queries/{id}/versions`,`GET /queries/{id}/versions/{version_no}`
- `POST /queries/{id}/preview`(草稿),`POST /queries/{id}/versions/{version_no}/preview`
- `GET /queries/{id}/references`
- 统一信封;错误码沿用平台约定。
## Permission Nodes
- `perm:data:emp:watchman.query.read`
- `perm:data:emp:watchman.query.write`
- `perm:data:emp:watchman.query.publish`
- `perm:data:emp:watchman.query.preview`
## Acceptance Criteria
- A-016:参数/输出/限制 schema;未知字段拒绝。
- A-017:绑定、只读账户前提(配置层)、超时与行数限制;不靠 SELECT 前缀。
- A-018:空/失败/非法类型分开;样例脱敏。
- A-019:列表与编辑 UI;越权不可保存。
- A-020:试跑预览 UI;不进入正式报警。
- 不可变版本:发布后历史不可改;新发布递增版本号。
- V009/V010/V011 口径的自动化或集成测试有证据。
## Assumptions
- 首版白名单机制:禁止通过参数改写标识符;若 SQL 需动态标识符,仅接受定义时声明的允许标识符集合(可为空=不允许动态标识符)。
- 默认限制:超时与 max_rows 有服务端上限封顶,防止表单填过大。
- 原型确认前不改正式 Vue 查询页;用户确认计划并要求执行全部切片后,S4 产出原型,S5 在原型落地后实现(若原型与冻结 UX 一致则连续推进)。
## Risks And Stop Conditions
- 注入/任意 SQL 风险:执行器与评审必查。
- 迁移/权限/熔断边界:`risk_score>=4` 切片在 autonomous 下仍停片际确认(实现后片审再续)。
- 禁止真实生产库破坏性操作;禁止秘密入库。
@@ -0,0 +1,30 @@
# M04 MUST-FIX Recheck
## Verdict
PASS
## Scope
Bounded recheck of the two MUST-FIX findings in `review-module-m04.md`; this is not a new module-wide review.
## Findings Closed
1. **Immutable query versions — closed.**
- Migration `20261118_0007` revokes `UPDATE`/`DELETE` from `watchman_app` and installs a statement-level `BEFORE UPDATE OR DELETE OR TRUNCATE` rejection trigger.
- The trigger also rejects mutations attempted by the migrator/table-owner, so a later privilege grant cannot bypass the append-only boundary.
- Regression coverage verifies app-role Core and ORM mutation failures, unchanged stored SQL, allowed inserts, and owner-side update/delete/truncate rejection.
2. **SQL Server preview write risk — closed.**
- `run_query` refuses SQL Server immediately after datasource usability checks, before template validation, secret decryption, or any source connection, with `engine_readonly_unsupported`.
- `queries/drivers.py` has no SQL Server runner, so direct `fetch_rows` calls also fail without opening a connection. The M03 connectivity probe remains separate and unchanged.
- Regression coverage exercises SELECT, UPDATE, DELETE, and `EXEC` refusal plus the API outcome and no-connection path.
## Validation
- `uv run pytest tests/test_query_versions.py tests/test_query_execute.py tests/test_query_api.py -q`
- Result: **194 passed**; one pre-existing dependency deprecation warning from Starlette `TestClient`.
## Notes
No new high-severity issue was found in these remediations.
@@ -0,0 +1,46 @@
# M04 Module Review
## Verdict
FAIL
## Must-fix
1. **Published versions are not actually immutable at the persistence boundary** (confidence: 100)
- **Location:** `services/watchman/migrations/versions/20261118_0006_query_definitions.py:42`; `services/watchman/src/watchman/services/query_versions.py:23`; `services/watchman/src/watchman/services/queries.py:385`
- The migration grants `watchman_app` `UPDATE` on `query_versions` and installs no trigger or database rule to reject updates. The only guard is the standalone `forbid_version_content_mutation()` helper, but no production write path calls it. Any present or future application code using a SQLAlchemy session can therefore alter a published SQL snapshot and commit it.
- This violates D24's immutable-published-version requirement despite the absence of an HTTP update route.
- **Fix:** enforce append-only versions at the database boundary (for example, revoke UPDATE/DELETE for the application role, or add an update/delete-rejecting trigger with a narrowly controlled maintenance path). Add an integration test that attempts a direct ORM/Core update and proves it is rejected.
2. **SQL Server previews can execute writes when the saved datasource credentials have write access** (confidence: 98)
- **Location:** `services/watchman/src/watchman/queries/drivers.py:260`
- PostgreSQL and MySQL establish a read-only transaction before executing the submitted template. The SQL Server runner sends the template directly via `cur.execute(sql, params)` and has no equivalent server-side read-only transaction or application gate. `DataSource.read_only_intent` is only stored/displayed and is never checked or verified before execution (`services/watchman/src/watchman/services/datasources.py:303`, `services/watchman/src/watchman/queries/execute.py:151`).
- A single-statement `UPDATE`, `DELETE`, DDL, or an executing stored procedure is accepted by the template parser and will mutate a SQL Server datasource whenever its configured login has write privileges. Parameter binding prevents value injection; it does not make arbitrary SQL read-only. This violates the read-only-preview boundary.
- **Fix:** do not allow SQL Server preview until a server-enforced read-only execution method is available, or require and verify a least-privileged read-only login as an executable precondition. Add a live SQL Server regression test proving a write statement cannot change data.
## Should-fix
None.
## Notes
- Review covered the supplied M04 backend, API/auth, datasource-reference, frontend, tests, migrations, and task/documentation scope.
- The reviewed API routes correctly restrict query operations to `watchman-admin`; parameter values are bound rather than text-spliced; preview outcomes keep empty, illegal-type, and failure distinct; and preview audit payloads omit SQL, parameters, and rows.
- Existing test results were provided by the orchestrator. This review did not re-run them.
## Remediation
Both must-fix findings were addressed (no commit made).
1. **Immutable `query_versions` at the DB boundary** — new migration `20261118_0007_query_versions_immutable`:
- `REVOKE UPDATE, DELETE` on `query_versions` from `watchman_app`; `SELECT, INSERT` re-asserted.
- Statement-level `BEFORE UPDATE OR DELETE OR TRUNCATE` trigger (`trg_query_versions_append_only`) that always raises `restrict_violation` (23001), so it also stops the table owner and any future grant, even when forced RLS hides all rows.
- Downgrade drops trigger and function and restores the 0006 grants (round-trip upgrade/downgrade/upgrade verified locally).
- Tests (`test_query_versions.py`): app-role privilege matrix; Core and ORM UPDATE/DELETE fail with SQLSTATE 42501 and the stored SQL is unchanged; INSERT of a new version still works; the owner (migrator) is rejected by the trigger for UPDATE/DELETE/TRUNCATE.
- Because the app role can no longer delete versions, test cleanup now uses a superuser purge (`tests/_privileged_cleanup.py`, `session_replication_role = replica`); there is no application maintenance path.
2. **SQL Server read-only boundary** — chosen fix: refuse, do not gate on statement text.
- `run_query` returns `failure_kind = engine_readonly_unsupported` (fixed safe message, no details from the driver) for `engine == "sqlserver"` right after `assert_usable`, before validation, secret decryption or any connection. The circuit is untouched.
- `_run_sqlserver` was removed from `queries/drivers.py`, so `fetch_rows` also raises `UnsupportedDataSourceError` for SQL Server: no write path exists even if the guard were bypassed. The M03 probe (`datasources/probe.py`) is unchanged.
- Tests: `run_query` on a sqlserver datasource is refused for SELECT, UPDATE, DELETE and EXEC with no driver/secret access; `fetch_rows("sqlserver")` opens nothing; an API preview test confirms the refusal outcome and a single audit event.
Validation: `uv run pytest` in `services/watchman` — 456 passed. Not covered: a live SQL Server test (none needed, since execution is refused); the frontend has not been checked for display of the new `failure_kind`.
@@ -0,0 +1,32 @@
# M04 Slice S1 Review Note (coder self-check)
Status: implemented; awaiting independent review (not a review verdict).
## Files created
- `services/watchman/src/watchman/models/query.py` — `QueryDefinition`, `QueryVersion`, `VERSION_CONTENT_COLUMNS`
- `services/watchman/migrations/versions/20261118_0006_query_definitions.py` — revises `20261118_0005`
- `services/watchman/src/watchman/services/query_versions.py` — `forbid_version_content_mutation`, `assert_version_immutable`
- `services/watchman/tests/test_query_versions.py` — 28 tests
## Files changed
- `services/watchman/src/watchman/models/__init__.py` — export new models
## Design notes
- `datasource_id` and `definition_id` FKs are `ON DELETE RESTRICT`; extra index `ix_query_definitions_datasource_id`.
- Both tables: ENABLE + FORCE RLS, `tenant_isolation` policy, full CRUD grant to `watchman_app`.
- `query_versions` has no `updated_at`. Immutability is enforced only by the service helper (frozen: content columns plus `tenant_id`, `definition_id`, `version_no`, `published_at`, `published_by`). It is NOT enforced at DB level because UPDATE is granted per the slice spec; direct SQL/ORM writes bypass the helper. Later slices must route all version writes through the service layer. A DB trigger is a possible hardening for the reviewer to consider.
- `latest_published_version_no` is not FK-linked to `query_versions` (set by publish logic in S3).
## Validation
- `uv run alembic upgrade head` — PASS (to `20261118_0006`); downgrade to `0005` then upgrade again — PASS.
- `uv run pytest tests/test_query_versions.py` — 28 passed.
- `uv run pytest` (full) — 290 passed, 1 pre-existing deprecation warning.
- No real passwords; datasource rows use a placeholder ciphertext and synthetic host/user.
## Scope check
- Only `models/`, `migrations/`, `services/query_versions.py` (explicitly requested), `tests/` touched. No API routes, executor, frontend, M03 circuit changes, or git commits.
@@ -0,0 +1,71 @@
# M04 Slice S2 — 只读执行器:实现自检记录
状态:实现完成,待独立 review(本文件是 coder 自检,不是独立审查结论)。未 commit。
## 变更文件
新增:
- `services/watchman/src/watchman/queries/__init__.py`(边界说明、导出)
- `services/watchman/src/watchman/queries/result.py`(`QueryRunResult`、状态/failure_kind 常量)
- `services/watchman/src/watchman/queries/schema.py`(param/output schema 解析、值类型校验)
- `services/watchman/src/watchman/queries/template.py`(模板扫描、`:name` 绑定、`{{ident}}` 白名单、单语句检查)
- `services/watchman/src/watchman/queries/drivers.py`(PG/MySQL/SQL Server 单语句执行与失败分类)
- `services/watchman/src/watchman/queries/execute.py`(`run_query` 编排)
- `services/watchman/tests/test_query_execute.py`
修改(薄改):
- `services/watchman/src/watchman/services/datasources.py`:新增 `build_probe_target(row)`、`record_connection_failure(session, datasource_id, category)`;未改既有函数。
未触碰:路由、前端、`query_definitions` schema/迁移、`.env*`。
## 行为摘要
`run_query` 顺序:`assert_usable` → 限制/schema/参数/标识符校验 → 内存解密 → `commit`(网络调用期间不持有事务)→ 执行(`max_rows+1`)→ 分类。
| 情形 | status | failure_kind |
| --- | --- | --- |
| 有行且符合输出契约 | success | — |
| 0 行 | empty | — |
| 声明列类型不符(details 仅含字段名/期望类型/实际 Python 类型名/首个违规行号,不含值) | illegal_type | — |
| 数据源停用/熔断打开(不连接、不读密钥) | failure | disabled / circuit_open |
| 校验失败(未知参数、缺必填、类型错、`{{x}}` 不在白名单、多语句、非法限制/schema) | failure | validation |
| 连接 auth/timeout/unreachable/rejected | failure | auth_failed / timeout / unreachable / rejected,**记入熔断** |
| 连接中途断开 | failure | unreachable,**记入熔断** |
| 语句超时(PG statement_timeout/MySQL read_timeout) | failure | timeout,**不记熔断** |
| SQL 语法/运行错误 | failure | sql_error(PG 附 SQLSTATE),**不记熔断** |
| 超过 `max_rows` | failure | limit_exceeded(不返回行) |
- 绑定:模板 `:name` → `%(name)s` 由驱动绑定;`::` 转型、字符串/引号标识符/注释/PG `$$` 内的 `:name`、`{{}}` 不当作占位符;无参数时不转义 `%`,有参数时转义为 `%%`。参数值不可能成为标识符(测试覆盖)。
- 白名单:`{{ident}}` 必须在 `allowed_identifiers` 且匹配 `^[A-Za-z_][A-Za-z0-9_]*$`,按引擎加引号(`"x"` / `` `x` `` / `[x]`);空列表=不允许;校验发生在连接之前。
- 只读:PG 用 `BEGIN READ ONLY` + `SET LOCAL statement_timeout`,结束 rollback;MySQL `SET SESSION TRANSACTION READ ONLY` + `START TRANSACTION READ ONLY` + 尽力设置 `MAX_EXECUTION_TIME`;SQL Server 无会话级只读,依赖只读账户(A-017 配置层前提)。不以 `SELECT` 前缀判定安全。额外加了“必须单语句”的结构检查(允许末尾 `;`)。
- 限制:`timeout_ms`/`max_rows` 必须是 ≥1 的 int,超过 `MAX_TIMEOUT_MS`/`MAX_ROWS_LIMIT` 被封顶;其余视为 `validation`。
- 日志:仅记录引擎、数据源 id、状态、行数;不记口令、连接串、参数值、结果集。
## 验证
- `uv run pytest tests/test_query_execute.py`:71 passed(含对 `WATCHMAN_TEST_PG_*` 本地源库的真实执行:绑定防注入、`%` 转义、类型参数、空/illegal_type/sql_error 三分、行数上限、语句超时不记熔断、会话只读(CREATE TABLE 被拒、`transaction_read_only=on`)、错误口令 auth_failed 记账、端口不可达记账)。
- `uv run pytest`(全量):361 passed,无失败。
- 覆盖要求映射:参数含 SQL 片段不改结构(模板测试+fake+live);空/失败/illegal_type 区分;disabled/circuit 拒绝且驱动未被调用;未知参数;`{{ident}}` 不在白名单/空白名单拒绝。
- MySQL 仅用 fake 驱动测试(连接 auth 映射、只读 SET、语法错误、连接丢失 vs read_timeout);SQL Server 未做任何自动化测试(无环境);二者的真实库行为 **NOT_RUN**。
## 设计决定/需要 reviewer 与用户确认的点
1. **`nullish` 语义未在需求中定义**:当前实现为“该列不做类型约束”;另外 SQL `NULL` 对所有声明类型都通过类型检查(认为 NULL 是缺值而非类型错误)。若产品想要“只能为 NULL”或“非 NULL 才算合法”,需改 `schema.check_output_value`。
2. **成功不记账**:按任务说明只对连接类失败调用 `record_probe_outcome`(`update_last_test=False`,不改 `last_test_*`);成功的预览不会重置失败计数。
3. **语句超时不算连接类失败**:慢查询/运行时超时不开闸;连接阶段超时和连接丢失才记入。MySQL `read_timeout` 与连接中途断开在驱动层难区分,按“超时链→timeout(不记);2006/2013 无超时链→unreachable(记)”处理。
4. **`param_schema[].required` 缺省为 true**(更严格);`required=true` 且带 `default` 时,缺参仍拒绝(按字面规则)。`boolean` 严格要求 bool(MySQL tinyint 返回 int 会判 illegal_type);`integer` 不接受 Decimal。
5. **`run_query` 内部 `commit`**:校验失败/连接失败记账后都会 commit,以免熔断计数随调用方丢弃结果而丢失;S3 路由无需再为熔断额外提交,但应知道会话已被提交。
6. `run_query` 对查询类问题**返回** `QueryRunResult`,不抛错;`NotFoundError`(未知数据源)和 `DatasourceSecretUnavailableError` 仍向上抛,由 S3 映射信封。
7. `drivers.py` 复用了 `watchman.datasources.probe` 的私有分类助手(`_classify_after_failure` 等),使连接失败分类与探测一致;若后续希望公开,可在 probe 中提升为公共 API(本片未改 probe)。
8. 结果行中 `Decimal→float`、`bytes→hex`、日期时间→ISO 字符串、其他→`str`;输出契约之外的列原样返回(脱敏策略留给 S3/预览层)。
9. 同名重复列只保留最后一个值(dict)。
## 残余风险
- 只读保证依赖数据库账户权限:PG 事务内用户 SQL 无法在单语句内切回读写,但仍应使用只读账户(配置层)。
- 无参数模板时 psycopg 可能走简单协议;已由“单语句”结构检查约束,但该检查是词法级的,不是完整 SQL 解析。
- SQL Server 路径无自动化证据。
## 文档同步
无设计语义变化需要更新 `docs/`;M04 任务卡进度由主 Agent 更新。
@@ -0,0 +1,82 @@
# M04 Slice S3 — API、权限、引用回填:实现自检记录
状态:实现完成,待独立 review(本文件是 coder 自检,不是独立审查结论)。未 commit。
## 变更文件
新增:
- `services/watchman/src/watchman/services/queries.py`(定义 CRUD、启停、publish、版本读取、预览编排、序列化)
- `services/watchman/src/watchman/api/routes/queries.py`(`/queries` 路由,`extra="forbid"` 请求模型)
- `services/watchman/tests/test_query_api.py`(84 个用例)
修改:
- `auth/access.py`:四个节点常量 + `require_query_read/write/publish/preview`(仅 `watchman-admin`)
- `auth/principal.py`:`require_query_reader/writer/publisher/previewer`;把 `_load_session_roles` 的会话读取抽成 `_load_session`(返回 login_name + roles,行为不变);`require_query_publisher` 返回 login_name 供 `published_by`
- `api/app.py`:注册 `queries.router`
- `services/datasources.py`:`list_references` 回填查询条目 `{type:"query", id, name, enabled}`,按 name 排序,仅本租户
- `api/routes/datasources.py`:仅 references 路由 docstring
未触碰:S1 模型/迁移、`query_versions.py`、`queries/` 执行器包、前端、`.env*`、`docs/`。
## 路由与契约
| 路由 | 权限 | 说明 |
| --- | --- | --- |
| `GET /queries?enabled=` | read | 摘要列表(不含草稿内容) |
| `POST /queries` | write | 创建启用的未发布定义 |
| `GET /queries/{id}` | read | 摘要 + `draft{sql_template,param_schema,output_schema,allowed_identifiers,timeout_ms,max_rows}`,含 `latest_published_version_no` |
| `PATCH /queries/{id}` | write | name/description/datasource_id/草稿六字段;不含 enabled 与任何版本字段 |
| `POST /{id}/disable|enable` | write | |
| `POST /{id}/publish` | publish | 返回完整冻结版本 |
| `GET /{id}/versions`、`/{id}/versions/{n}` | read | 摘要(新→旧)/完整内容 |
| `POST /{id}/preview`、`/{id}/versions/{n}/preview` | preview | body `{params:{}}`(可省略,`extra=forbid`) |
| `GET /{id}/references` | read | `{id, items: []}` |
- 输入字段名用 `sql_template` 等(不带 `draft_`),输出放在 `draft` 对象里,键名相同,便于 GET → PATCH 往返。
- 未知/越权字段(tenant_id、enabled、version_no、published_by、latest_published_version_no、`draft_*`)→ 40000。
- 版本无任何 PATCH/PUT/DELETE/POST 路由(测试断言 404/405);唯一写入门(定义 PATCH)拒绝版本形字段。
- 信封、错误码沿用既有:无会话 41000;非 admin 42000 + `permission_node`;404 用 `NotFoundError`(含跨租户、非法 UUID);重名 409 `duplicate_name`;预览停用 409 `reason=disabled`。
## 行为摘要
- **创建/PATCH 校验**:复用 S2 `parse_param_schema/parse_output_schema/parse_allowed_identifiers`(未知键、重复、非法类型→40000 reason);SQL 模板不得全空白;`timeout_ms/max_rows` 必须是 ≥1 的严格 int(拒绝 bool/0/负数),超过服务端上限按 S2 口径**封顶**(不拒绝);数据源须存在于本租户且 `kind=database`,否则 400(`datasource_not_found`/`datasource_not_database`)。不对 SQL 模板做深度解析(模板问题在预览中以 `failure/validation` 呈现)。
- **publish**:锁定定义行(`FOR UPDATE`)→ 重新校验草稿 → `version_no = (latest or 0)+1` → 只 INSERT 版本行,复制 draft 六字段 → 更新 `latest_published_version_no`;`published_by` = 会话 `login_name`(截断 128)。版本行没有任何更新路径;`UNIQUE(definition_id, version_no)` 兜底并发(映射 409 `version_conflict`)。停用的定义仍可发布。
- **预览**:先断言定义启用(否则 409,不运行、不审计)→ 把草稿/版本内容拷出 ORM 对象(`run_query` 会 commit)→ 调 S2 `run_query`(定义当前绑定的数据源)→ 写审计 → 路由 commit。`QueryRunResult` 映射:
- `success`/`empty`:`columns, rows, row_count, masked_columns`
- `illegal_type`:`columns, details.fields`(仅字段名/类型,无值)
- `failure`:`failure_kind, details`
- 失败的运行是 HTTP 200 的结果(`status=failure`),不是 API 错误。
- **样例脱敏**:输出契约没有敏感标记,采用按列名的简单策略(`password/pwd/secret/token/credential/api_key/private_key/id_card/phone/mobile/email`,大小写不敏感),非 NULL 值替换为 `***`,并返回 `masked_columns`。S2 说明过脱敏留给本层。
- **审计**:`query.create`(id,name,datasource_id)、`query.update`(id,name,**字段名列表**,无 SQL)、`query.enable/disable`(id,name)、`query.publish`(id,name,version_no)、`query.preview`(**仅** id、status,版本预览加 version_no;不含 name、SQL、参数、行、消息)。幂等键由服务端生成。
- **数据源 references**:`{id, items:[{type:"query",id,name,enabled}]}`,随查询改绑/停用实时变化,不含其他租户。查询侧 references 仍恒为空。
- 时间戳序列化统一转 UTC ISO(新写入值与重新读取值时区会不同,否则前后不相等)。
## 验证
- `uv run pytest tests/test_query_api.py`:84 passed
- `uv run pytest`(全量):**445 passed**(S2 后基线 361 + 本片 84),无失败;无需网络或真实源库
- 覆盖:节点字符串与角色规则;12 条路由 × 匿名 41000;12 条路由 × 4 类非 admin 42000 带正确节点且数据未变;create/list/get/patch/enable/disable+`?enabled=` 过滤;创建与 PATCH 的未知字段/空值/非法 schema/限制/数据源校验;重名 409;publish v1→v2、草稿后改不影响 v1、版本列表与详情、published_by、审计;版本不可通过任何端点改;预览成功/空/illegal_type/failure 四种形状(fake `run_query`);脱敏;预览审计无数据;版本预览用冻结内容、草稿预览用草稿;停用定义 409 且不运行不审计;真实 `run_query` 的无网络路径(unknown_param 校验失败、数据源停用);查询 references 为空;数据源 references 列出/改绑/停用/跨租户;跨租户 id 404。
- 未运行:对真实源库的 HTTP 预览成功路径(S2 的 live 测试覆盖执行器本身;本片用 fake)。浏览器/前端:不在本片。
## 设计决定/需要 reviewer 与用户确认的点
1. **输入/输出字段命名**:输入 `sql_template…`,输出 `draft.{…}`;S4 原型与 S5 按此口径。若希望扁平 `draft_*` 需改序列化。
2. **版本不快照 datasource_id**:版本预览使用定义**当前**绑定的数据源。若用户后来改绑数据源,旧版本预览会跑在新数据源上。需求未要求版本冻结数据源(S1 表也没有该列);如需冻结应回到 S1 加列。
3. **停用定义仍可发布**,只拒绝预览。需求仅说停用后不可预览。
4. **数据源停用/熔断**在预览中是 `status=failure, failure_kind=disabled|circuit_open`(S2 语义,HTTP 200),而**查询定义停用**是 409。两者故意不同:前者是运行结果,后者是调用前置条件。
5. **绑定数据源时只要求存在且 `kind=database`**,不要求当前 enabled/熔断闭合(那是运行时状态,由 `assert_usable` 把关)。需求写“可用数据库数据源”,如要求创建时必须 usable 需确认。
6. **脱敏策略是列名正则**,可能漏掉不含关键词的敏感列、误伤含关键词的列;输出契约尚无敏感标记。
7. **PATCH 空 body 为成功空操作**(会写一条 `query.update`,`fields: []`),与数据源 PATCH 一致。
8. `principal.py` 的 `_load_session_roles` 被改写为 `_load_session` 的薄包装(行为不变,数据源/平台测试全绿)。
9. `preview` 失败信息只经 S2 的固定文案/安全 details 透出;若 S2 details 扩展含值需同步检查。
10. 没有写权限节点登记到公司 `standards://api/permission-nodes`(本次 sy-standards 检索未执行;节点串按任务指令原样使用)。
## 残余风险
- 预览会对真实源库执行用户 SQL(只读保证依赖 S2 与只读账户);本片未新增任何绕过 `assert_usable` 的路径。
- 并发 publish 依赖行锁+唯一约束;未写并发测试(测试库单进程)。
- `published_by` 取 `login_name`(非 Casdoor subject);如审计需要稳定主体 id 应改为 subject。
## 文档同步
无设计语义变化需要更新 `docs/`;`docs/progress.md`、M04 任务卡、`knowledge-map` 由主 Agent 更新。
@@ -0,0 +1,16 @@
# Review S4 — HTML prototype
## Status
PASS — static prototype delivered for maintainer UX confirmation.
## Files
- `.task/2026-11-18/m04-queries/prototype/index.html`
- `.task/2026-11-18/m04-queries/prototype/README.md`
## Notes
- Covers gate, empty/list, draft edit, version readonly, preview outcome switcher, publish confirm.
- Follows D22 footer/list button rules and M03 prototype interaction pattern.
- User execute-all-todos authorization (2026-11-18): S5 proceeds using prototype defaults documented in README (preview saved draft; disable allows click-then-reject for preview; name-based masking).
@@ -0,0 +1,26 @@
# Review S5 — Vue queries console
## Status
PASS_WITH_WARNINGS — module landed; unit/typecheck verified in session; e2e evidence pending formal S6 run.
## Scope delivered
- `web/apps/console/src/queries/**` — list/edit/gate/version/preview helpers
- Routes under `/queries` in `router.ts`; nav/crumbs in `AppShell.vue`
- `allowsQueries` admin gate in `session.ts`
- Locales (四语言) + `docs/current/frontend-ui.md` 查询节
- Unit specs: validation/payload/client/errors/locales
- E2E: `web/apps/console/e2e/queries.spec.ts` (mocked API)
## UX defaults locked for S5
- Preview saved draft; dirty form disables preview / prompts save before publish
- Disabled: list preview disabled; detail preview click → 409 explanation
- Masking via API `masked_columns`
## Remaining for S6
- Formal Playwright run + screenshots under `docs/evidence/M04/ui/`
- Independent module review across S1–S5
- Full pytest regression
+32
View File
@@ -0,0 +1,32 @@
{
"taskId": "2026-11-18/m04-queries",
"module": "M04",
"title": "查询定义与采集模块",
"type": "feature",
"tier": "L",
"phase": "final-approval",
"allowedToCode": false,
"currentSlice": "S6-done",
"proposedNextSlice": null,
"lastGate": "module-review-pass-awaiting-final-approval",
"status": "VERIFIED_LOCAL",
"gatePolicy": {
"selected": "autonomous",
"effective": "autonomous",
"recommended": "balanced",
"finalApprovalRequired": true,
"allowTaskOverride": true
},
"validation": {
"pytest": "456 passed",
"consoleUnitQueries": "51 passed",
"e2eQueries": "16 passed",
"evidence": "docs/evidence/M04/ui/"
},
"notes": [
"D24 parameterized SQL + immutable versions; formal collection deferred to M08",
"Module review FAIL then remediations: DB append-only versions; SQL Server preview refused",
"Recheck PASS"
],
"updatedAt": "2026-11-18T07:30:00Z"
}
@@ -0,0 +1,42 @@
# Context Pack — m04-version-activate
## Task goal
去掉查询草稿/发布两步;保存即新版本并生效;支持版本激活(列表+详情)。
## Requirement / plan
- `.task/2026-11-18/m04-version-activate/requirement.md`
- `.task/2026-11-18/m04-version-activate/implementation-plan.md`
- D26 in `docs/decisions.md`
## Allowed modification scope
- `services/watchman/src/watchman/models/query.py`
- `services/watchman/src/watchman/services/queries.py`
- `services/watchman/src/watchman/api/routes/queries.py`
- `services/watchman/migrations/versions/20261118_0008_*.py`
- `services/watchman/tests/test_query_*.py`
- `web/apps/console/src/queries/**`
- `web/apps/console/locales/**`
- `web/apps/console/e2e/queries.spec.ts`
- `docs/decisions.md`, `docs/progress.md`, `docs/tasks/M04.md`, `docs/current/frontend-ui.md`
- `.task/active.json` and this task directory
## Forbidden
- Dropping `draft_*` columns
- New permission node codes
- Scene/cron/alarm modules
- Auto commit/push
## Current approved slice
- All slices S1–S4 completed; phase `finalization`.
- Awaiting user final approval for DONE_LOCAL / optional commit.
## Validation
- query* pytest: 201 passed
- console unit `src/queries`: 52 passed
- e2e `queries.spec.ts`: 16 passed
@@ -0,0 +1,10 @@
# Implementation Plan
| Slice | Content | gateClass | risk_score |
|-------|---------|-----------|------------|
| S1 | migration + save-as-version / activate service | boundary-sensitive | 4 |
| S2 | API reshape | standard | 3 |
| S3 | console UI | standard | 3 |
| S4 | tests + docs | standard | 2 |
gatePolicy.selected=balanced(用户批准整份 plan 后连续执行)。
@@ -0,0 +1,28 @@
# M04 增补:去掉草稿 + 版本激活
## Goal
查询定义不再使用「草稿/发布」两步。保存内容即生成不可变新版本并自动设为当前生效;可激活任一历史版本;列表与详情均可切换。
## Decisions
- D26(1=C,2=A):版本切换=激活 `current_version_no`;保存内容=新版本且自动 current。
- 版本行仍不可变(D24 库级约束保留)。`draft_*` 列本轮保留并镜像 current,对外不暴露 draft。
## In Scope
- `current_version_no` 迁移与回填。
- create → v1 + current;save-as-version;activate;去 publish/draft API 形状。
- 控制台:保存/激活/列表切换版本;文案去草稿/发布。
## Out Of Scope
- 物理删除 `draft_*` 列。
- 场景采集(M08)。
- 新权限点编码。
## Acceptance
- 新建保存即有 v1 且为 current;再保存得 v2 且 current=v2。
- 激活旧版后列表/详情/默认预览跟 current。
- UI 无保存草稿/发布/返回草稿;列表可切换版本。
@@ -0,0 +1,22 @@
{
"taskId": "2026-11-18/m04-version-activate",
"type": "feature",
"phase": "done",
"allowedToCode": false,
"currentSlice": "S4",
"completedSlices": ["S1", "S2", "S3", "S4"],
"status": "DONE_LOCAL",
"validation": {
"pytest_query": "201 passed",
"unit_queries": "52 passed",
"e2e_queries": "16 passed"
},
"gatePolicy": {
"selected": "balanced",
"effective": "balanced",
"recommended": "balanced",
"finalApprovalRequired": true,
"allowTaskOverride": true
},
"updatedAt": "2026-11-18T10:31:00Z"
}
+8 -7
View File
@@ -1,16 +1,17 @@
{
"taskId": "2026-11-17/m03-datasource",
"taskId": "2026-11-18/m04-version-activate",
"type": "feature",
"phase": "done",
"allowedToCode": false,
"currentSlice": "done",
"lastGate": "done-local",
"nextCommand": "none — M03 DONE_LOCAL; pick next module from docs/tasks/INDEX.md",
"currentSlice": "S4",
"lastGate": "user-approved-done-local",
"nextCommand": "start M05 when ready",
"gatePolicy": {
"selected": "autonomous",
"effective": "autonomous",
"selected": "balanced",
"effective": "balanced",
"recommended": "balanced",
"finalApprovalRequired": true,
"allowTaskOverride": true
},
"updatedAt": "2026-11-18T04:50:00Z"
"updatedAt": "2026-11-18T10:31:00Z"
}
+22 -1
View File
@@ -8,7 +8,18 @@
详情页和表单页的页面按钮放在页脚,并居中。包括返回、保存、草稿测试、已保存测试、停用、启用。页脚在纵向滚动区域之外,正文滚动时按钮保持可见,不跟着滚走,也不要散落在表单中间或标题栏里。
列表页导航为「Watchman / 数据源」。详情页为「Watchman / 数据源 / 详情」,新建页为「Watchman / 数据源 / 新建」。不要在导航下方再放一块重复的页面标题。
列表页导航为「预警平台 / 数据源」。详情页为「预警平台 / 数据源 / 详情」,新建页为「预警平台 / 数据源 / 新建」。不要在导航下方再放一块重复的页面标题。
侧栏品牌:左侧导航顶部放 logo(`assets/logo.jpg`)+ 文案「预警平台」(i18n `appName`)。登录信息与「退出」放在左侧导航栏底部,不放顶栏。
## 列表页(默认,D25)
除非用户对本页另有说明,控制台业务列表一律满足:
1. **筛选条件**:表格上方工具条左侧提供常用查询条件(至少含名称类模糊搜索;有归属/类型/状态列时一并提供下拉)。「新建」等页面按钮靠右。筛选为草稿态:点「查询」才请求后端,「重置」清空条件并重新请求;禁止输入即筛。无匹配与真正空列表文案区分。
2. **表头排序与分页**:数据列 `sortable="custom"`,排序与分页一律走后端 SQL(`sort_by`/`sort_order`/`page`/`page_size`);操作列不排序。禁止只对当前页做前端排序。分页用 `ElPagination`(`total, sizes, prev, pager, next` + `background`)。
3. **操作列宽度**:按行内 link 按钮数量取固定 `width`(`align="right"`),用 `actionsColumnWidth(n)`(`src/tableLayout.ts`):1→72,2→120,3→168,4→216(约 48px/钮 + 24 边距)。禁止用过大 `min-width` 把操作列撑宽。
4. **行内操作**:只放本模块明确需要的行操作;删除、版本切换等若需求未授权则不做。
## 数据源(D23)
@@ -17,9 +28,19 @@
- 停用后可「启用」,不必先测通。
- host 校验只做必填。熔断三参数仅详情可编辑;开闸时展示恢复时间。
- 周期巡检开关与 Cron 只在后端配置,控制台不提供巡检配置页。
- 列表筛选:名称模糊、引擎、状态;点「查询/重置」才生效;表头服务端排序;底部分页。
## 密码框
使用 Element Plus 的 `el-input`,`type="password"`,并打开 `show-password`。不要自绘密码框和查看按钮。
已保存的密码不回填。编辑时可以用固定长度占位,聚焦后清空;留空表示不修改。
## 查询(M04,D26)
- 列表导航为「预警平台 / 查询」,详情「… / 查询 / 详情」,新建「… / 查询 / 新建」,版本只读「… / 查询 / 详情 / 版本 vN」(「详情」或「返回查询」回到编辑页)。列表页表格上方左侧为名称模糊/数据源/状态筛选+「查询/重置」,「新建」靠右;表头服务端排序,底部分页;操作列三钮(打开/切换版本/预览)。「切换版本」打开对话框列出版本并可激活。列显示「当前版本」(`current_version_no`)。已停用行的「预览」禁用,用 `title` 说明。无删除、无「保存草稿/发布」文案。
- 编辑页脚顺序:返回列表、保存、停用/启用、试跑预览。保存内容即生成下一不可变版本并自动设为当前;仅改名称/说明/数据源则 PATCH 元数据。新建时「试跑预览」置灰,需先保存。版本只读页脚:返回列表、返回查询、激活此版本(非当前时)、试跑预览;不放保存。
- 停用要确认,启用不需要确认;停用后可再启用。版本区可「激活此版本」;不设单独「发布」按钮。
- 试跑预览默认使用已保存的**当前版本**:表单有未保存修改时「试跑预览」禁用并提示先保存。版本只读页预览该冻结版本。已停用的查询在详情页「试跑预览」仍可点,服务端拒绝(409),预览区说明「已停用,未执行」。
- SQL Server 数据源本轮拒绝查询试跑(`engine_readonly_unsupported`),界面展示对应失败文案;连接测试仍走数据源页。PostgreSQL/MySQL 使用服务端只读事务执行预览。
- 预览结果五类分开显示:成功(样例表,脱敏列加标签)、空结果(不是失败)、非法类型(契约不符明细)、失败(超时/连接/SQL 等分开,连接类注明计入熔断)、拒绝(停用、熔断中)。控制台不显示服务端消息原文。
+3
View File
@@ -29,6 +29,9 @@
| D21 | M03 第一阶段:交付后端和确认后的界面。只实现数据库来源,引擎为 PostgreSQL、MySQL、SQL Server,其他种类只留扩展位。凭证用平台库加密字段,API 不回显,日志脱敏。引用用空列表。允许为测试创建隔离库表;SQL Server 可用本机 Docker。正式 Vue 之前必须先确认 HTML 原型。源库口令不写入仓库 | 2026-11-17 用户确认阶段边界与四项口径 |
| D22 | 列表页的页面按钮放在表格上方。详情页和表单页的页面按钮放在页脚并居中,且位于纵向滚动区域之外,滚动正文时保持可见。表格行内操作留在该行。密码框使用 Element Plus `el-input` 的 `type="password"` 与 `show-password`,不自绘密码框 | 2026-11-18 用户确认:页脚只用于详情页,按钮居中 |
| D23 | M03 增补:保存前草稿连接测试(不写 last_test、不入熔断账);停用可逆启用且无需先测通;host 校验仅必填;周期巡检由后端配置开关 + Cron,失败只更新 last_test 与审计、本轮不发企微;熔断与停用解耦,认证失败计入,默认窗口 300s/阈值 3/冷却 600s,开闸期禁测试与业务使用,到期自动熄闸;熔断三参数在数据源详情配置;本轮全进 M03 | 2026-11-18 用户确认 Q1–Q6、C1、C2=A 及详情配置熔断 |
| D24 | M04:查询正文采用参数化 SQL 模板(命名参数绑定;不可绑标识符白名单;不靠 SELECT 前缀)。本轮交付不可变查询版本(草稿可编辑,publish 生成只读快照;库级禁止 UPDATE/DELETE)。正式定时/场景采集留给 M08;本轮含定义 CRUD、版本、只读预览与配套 UI。执行必须经 M03 usable/熔断。仅 watchman-admin。正式 Vue 前须确认 HTML 原型。SQL Server 本轮不做查询试跑(无服务端强制只读会话),连接测试仍可用;预览仅 PostgreSQL/MySQL | 2026-11-18 用户确认 1=A、2b 及 Marionettist 计划;审查复审后收紧 SQL Server 与版本不可变 |
| D25 | 控制台业务列表默认:表格上方有筛选条件(至少名称模糊;有类型/归属/状态则一并提供),「查询/重置」按钮提交筛选(禁止输入即筛),「新建」等页面按钮靠右;表头 `sortable=custom` 走后端 SQL 排序并配合分页;操作列按按钮数固定宽度。用户对本页另有说明时从其说明。细则见 `docs/current/frontend-ui.md` | 2026-11-18 用户明确要求;同日补充查询/重置、服务端排序分页、操作列宽 |
| D26 | M04 增补:去掉查询「草稿/发布」两步。保存内容即插入下一不可变版本并自动设为 `current_version_no`;可激活任一历史版本为当前生效(详情与列表均可切换)。版本内容仍不可变。`draft_*` 列本轮保留并镜像 current,对外 API/UI 不暴露 draft。权限沿用既有 query write/publish,不新造权限点 | 2026-11-18 用户确认 1=C、2=A 并批准实现计划 |
## 冻结前/相关模块实现前必须确认
Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

+8 -6
View File
@@ -2,11 +2,11 @@
## 当前快照
- 当前阶段:M03 数据源配置 **DONE_LOCAL**(用户确认联调收尾并授权提交推送)。
- 当前大任务:无进行中模块大任务。上一完成:M03。再上一:M02。
- 用户授权:D21、D22、D23。数据源接口仅 `watchman-admin`。
- Git:本轮提交并推送后绑定候选 commit(见下方状态表)。
- 下一步:进入下一模块(按 `docs/tasks/INDEX.md`)前先读本台账与交接。
- 当前阶段:M04 查询定义与采集 **DONE_LOCAL**(D24 查询模块 + D25 列表筛选排序 + D26 保存即版本/激活;用户确认可提交)。
- 当前大任务:无(M04 已完成)。下一候选:M05(见 `docs/tasks/INDEX.md`)。
- 用户授权:D21–D26。收尾任务 `gatePolicy.selected=balanced`。
- Git:用户授权 commit/push。
- 下一步:按 INDEX 进入 M05。
## 大任务状态
@@ -15,8 +15,10 @@
| M01 基础框架 | DONE_LOCAL | 实现 Composer;审查/复审异系列 | `8fb16f4` | PASS_WITH_WARNINGS(必改已关) | pytest 23;unit 8;e2e 3 | 已完成 |
| M02 统一登录与权限 | DONE_LOCAL | 主 Agent;复审 claude-opus | `f8e1c77` | 复审阻塞已由 D20 关闭 | pytest 58;unit 10;登录 Playwright 4 | 已完成 |
| M03 数据源配置 | DONE_LOCAL | 实现 Claude Sonnet;审查 GPT | `e6d37d1` | S1–S8 片审通过;用户联调收尾 | pytest 262+;console unit 39;datasources e2e 18;证据 `docs/evidence/M03/ui/` | 已完成 |
| M04 查询定义与采集 | DONE_LOCAL | 主 Agent 编排;D26 激活切片已实现 | 提交后回填 | 模块复审 PASS;D26 回归 pytest/e2e | query* pytest 201;queries unit 52;e2e queries 16;`docs/evidence/M04/ui/` | 已完成;下一 M05 |
## 当前阻塞
- O08:跨系列子 Agent 授权仍开放。
- O01–O07:业务口径,不阻塞已完成的 M01–M03。
- O01–O07:业务口径,不阻塞 M04 已冻结范围(D24/D26)。
- M04:SQL Server 查询试跑本轮明确不做(无服务端只读会话);连接测试仍可用。`draft_*` 列本轮保留镜像、未物理删除。
+29
View File
@@ -0,0 +1,29 @@
# M04 查询定义与采集模块
一个会话聚焦本模块。范围见 `.task/2026-11-18/m04-queries/requirement.md`(D24)与 `.task/2026-11-18/m04-version-activate/`(D26)。
## 内部步骤(主 Agent 根据现有代码安排)
- [x] 明确边界、依赖和复用方案(intake/requirement/plan/context-pack)。
- [x] S1 模型、迁移与不可变版本约束(含 0007 库级禁止 UPDATE/DELETE)。
- [x] S2 只读执行器(绑定、限制、三分语义、usable;SQL Server 试跑拒绝)。
- [x] S3 API、权限、引用回填。
- [x] S4 HTML 原型。
- [x] S5 前端与接口联调。
- [x] S6 模块整体独立 review、修复复审、正式测试与证据。
- [x] D26:去掉草稿/发布;`current_version_no`;保存出版本;激活;列表切换版本(S1–S4)。
- [x] 用户最终确认后主 Agent 标 DONE_LOCAL/交接。
## 目标与边界
- 已确认:D14、D19、D22、D23、D24、D25、D26。
- 已交付:参数化 SQL、不可变版本、`current_version_no` 激活、保存即生效、只读预览(PG/MySQL)、配套 UI(无草稿/发布两步)。
- 明确不做:场景 Cron 正式采集;映射/规则/报警/企微;任意脚本;SQL Server 查询试跑(连接测试仍可用);本轮不物理删除 `draft_*` 列。
## 证据与结论
- 任务产物:`.task/2026-11-18/m04-queries/`;增补 `.task/2026-11-18/m04-version-activate/`
- 审查:`reviews/review-s1.md` … `review-s5.md`;`review-module-m04.md`(初审 FAIL)→ 修复后 `review-module-m04-recheck.md` **PASS**
- 测试(D26 回归):query* pytest 201;console unit queries 52;e2e queries 16
- UI 证据:`docs/evidence/M04/ui/`
- 最终状态:**DONE_LOCAL**
@@ -0,0 +1,136 @@
"""Create query_definitions and query_versions with forced RLS.
Revision ID: 20261118_0006
Revises: 20261118_0005
Create Date: 2026-11-18
query_versions rows are immutable by contract. watchman_app still gets UPDATE so the ORM
and edge-case maintenance keep working; the service layer refuses content updates.
"""
from __future__ import annotations
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision: str = "20261118_0006"
down_revision: Union[str, None] = "20261118_0005"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
APP_ROLE = "watchman_app"
DEFINITIONS = "query_definitions"
VERSIONS = "query_versions"
def _enable_rls(table: str) -> None:
op.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")
op.execute(f"ALTER TABLE {table} FORCE ROW LEVEL SECURITY")
op.execute(
f"""
CREATE POLICY tenant_isolation ON {table}
FOR ALL
TO {APP_ROLE}
USING (tenant_id = current_setting('app.tenant_id', true))
WITH CHECK (tenant_id = current_setting('app.tenant_id', true))
"""
)
op.execute(f"GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE {table} TO {APP_ROLE}")
def upgrade() -> None:
op.create_table(
DEFINITIONS,
sa.Column(
"id",
postgresql.UUID(as_uuid=True),
server_default=sa.text("gen_random_uuid()"),
primary_key=True,
),
sa.Column("tenant_id", sa.String(length=64), nullable=False),
sa.Column("name", sa.String(length=128), nullable=False),
sa.Column("description", sa.Text(), nullable=True),
sa.Column(
"datasource_id",
postgresql.UUID(as_uuid=True),
sa.ForeignKey("data_sources.id", ondelete="RESTRICT"),
nullable=False,
),
sa.Column("enabled", sa.Boolean(), server_default=sa.text("true"), nullable=False),
sa.Column("draft_sql_template", sa.Text(), nullable=False),
sa.Column(
"draft_param_schema",
postgresql.JSONB(),
server_default=sa.text("'[]'::jsonb"),
nullable=False,
),
sa.Column(
"draft_output_schema",
postgresql.JSONB(),
server_default=sa.text("'[]'::jsonb"),
nullable=False,
),
sa.Column(
"draft_allowed_identifiers",
postgresql.JSONB(),
server_default=sa.text("'[]'::jsonb"),
nullable=False,
),
sa.Column("draft_timeout_ms", sa.Integer(), server_default=sa.text("10000"), nullable=False),
sa.Column("draft_max_rows", sa.Integer(), server_default=sa.text("100"), nullable=False),
sa.Column("latest_published_version_no", sa.Integer(), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
sa.UniqueConstraint("tenant_id", "name", name="uq_query_definitions_tenant_name"),
sa.CheckConstraint("draft_timeout_ms BETWEEN 1 AND 300000", name="ck_query_definitions_timeout"),
sa.CheckConstraint("draft_max_rows BETWEEN 1 AND 10000", name="ck_query_definitions_max_rows"),
sa.CheckConstraint(
"latest_published_version_no IS NULL OR latest_published_version_no >= 1",
name="ck_query_definitions_latest_version",
),
)
op.create_index("ix_query_definitions_datasource_id", DEFINITIONS, ["datasource_id"])
op.create_table(
VERSIONS,
sa.Column(
"id",
postgresql.UUID(as_uuid=True),
server_default=sa.text("gen_random_uuid()"),
primary_key=True,
),
sa.Column("tenant_id", sa.String(length=64), nullable=False),
sa.Column(
"definition_id",
postgresql.UUID(as_uuid=True),
sa.ForeignKey("query_definitions.id", ondelete="RESTRICT"),
nullable=False,
),
sa.Column("version_no", sa.Integer(), nullable=False),
sa.Column("sql_template", sa.Text(), nullable=False),
sa.Column("param_schema", postgresql.JSONB(), nullable=False),
sa.Column("output_schema", postgresql.JSONB(), nullable=False),
sa.Column("allowed_identifiers", postgresql.JSONB(), nullable=False),
sa.Column("timeout_ms", sa.Integer(), nullable=False),
sa.Column("max_rows", sa.Integer(), nullable=False),
sa.Column("published_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
sa.Column("published_by", sa.String(length=128), nullable=True),
sa.UniqueConstraint("definition_id", "version_no", name="uq_query_versions_def_version"),
sa.CheckConstraint("version_no >= 1", name="ck_query_versions_version_no"),
sa.CheckConstraint("timeout_ms BETWEEN 1 AND 300000", name="ck_query_versions_timeout"),
sa.CheckConstraint("max_rows BETWEEN 1 AND 10000", name="ck_query_versions_max_rows"),
)
_enable_rls(DEFINITIONS)
_enable_rls(VERSIONS)
def downgrade() -> None:
op.execute(f"DROP POLICY IF EXISTS tenant_isolation ON {VERSIONS}")
op.drop_table(VERSIONS)
op.execute(f"DROP POLICY IF EXISTS tenant_isolation ON {DEFINITIONS}")
op.drop_index("ix_query_definitions_datasource_id", table_name=DEFINITIONS)
op.drop_table(DEFINITIONS)
@@ -0,0 +1,63 @@
"""Make query_versions append-only at the database boundary.
Revision ID: 20261118_0007
Revises: 20261118_0006
Create Date: 2026-11-18
Published versions are immutable (D24). 0006 still granted UPDATE/DELETE to watchman_app and
relied on a Python helper nobody calls on a write path. Two independent layers now enforce it:
1. privileges: watchman_app keeps SELECT and INSERT only (UPDATE/DELETE revoked);
2. a statement-level BEFORE UPDATE/DELETE/TRUNCATE trigger that always raises, so even the
table owner or a future GRANT cannot change or remove a version. Statement level on
purpose: it fires even when forced RLS hides every row from the caller.
There is no application maintenance path. A superuser who must purge rows (test cleanup,
data-retention work) has to opt out explicitly with `SET LOCAL session_replication_role =
replica`, which is not available to the application or migrator roles.
"""
from __future__ import annotations
from typing import Sequence, Union
from alembic import op
revision: str = "20261118_0007"
down_revision: Union[str, None] = "20261118_0006"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
APP_ROLE = "watchman_app"
VERSIONS = "query_versions"
FUNCTION = "query_versions_reject_mutation"
TRIGGER = "trg_query_versions_append_only"
def upgrade() -> None:
op.execute(f"REVOKE UPDATE, DELETE ON TABLE {VERSIONS} FROM {APP_ROLE}")
op.execute(f"GRANT SELECT, INSERT ON TABLE {VERSIONS} TO {APP_ROLE}")
op.execute(
f"""
CREATE OR REPLACE FUNCTION {FUNCTION}() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION 'query_versions is append-only: published versions are immutable'
USING ERRCODE = 'restrict_violation';
END;
$$
"""
)
op.execute(
f"""
CREATE TRIGGER {TRIGGER}
BEFORE UPDATE OR DELETE OR TRUNCATE ON {VERSIONS}
FOR EACH STATEMENT EXECUTE FUNCTION {FUNCTION}()
"""
)
def downgrade() -> None:
op.execute(f"DROP TRIGGER IF EXISTS {TRIGGER} ON {VERSIONS}")
op.execute(f"DROP FUNCTION IF EXISTS {FUNCTION}()")
op.execute(f"GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE {VERSIONS} TO {APP_ROLE}")
@@ -0,0 +1,108 @@
"""Add current_version_no and backfill from drafts / latest published.
Revision ID: 20261118_0008
Revises: 20261118_0007
Create Date: 2026-11-18
D26: definitions point at the active version. Rows with no versions yet get v1 from draft_*.
"""
from __future__ import annotations
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "20261118_0008"
down_revision: Union[str, None] = "20261118_0007"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
DEFINITIONS = "query_definitions"
VERSIONS = "query_versions"
def upgrade() -> None:
op.add_column(
DEFINITIONS,
sa.Column("current_version_no", sa.Integer(), nullable=True),
)
op.create_check_constraint(
"ck_query_definitions_current_version",
DEFINITIONS,
"current_version_no IS NULL OR current_version_no >= 1",
)
# FORCE RLS would hide / block migrator writes; lift it for backfill only.
op.execute(f"ALTER TABLE {DEFINITIONS} NO FORCE ROW LEVEL SECURITY")
op.execute(f"ALTER TABLE {VERSIONS} NO FORCE ROW LEVEL SECURITY")
try:
# Definitions that already have published versions: current = latest pointer.
op.execute(
f"""
UPDATE {DEFINITIONS}
SET current_version_no = latest_published_version_no
WHERE latest_published_version_no IS NOT NULL
AND current_version_no IS NULL
"""
)
# Definitions with no version rows: freeze draft_* as v1 and point current at it.
op.execute(
f"""
INSERT INTO {VERSIONS} (
id, tenant_id, definition_id, version_no,
sql_template, param_schema, output_schema, allowed_identifiers,
timeout_ms, max_rows, published_at, published_by
)
SELECT
gen_random_uuid(),
d.tenant_id,
d.id,
1,
d.draft_sql_template,
d.draft_param_schema,
d.draft_output_schema,
d.draft_allowed_identifiers,
d.draft_timeout_ms,
d.draft_max_rows,
COALESCE(d.updated_at, d.created_at, now()),
'migration:20261118_0008'
FROM {DEFINITIONS} d
WHERE NOT EXISTS (
SELECT 1 FROM {VERSIONS} v WHERE v.definition_id = d.id
)
"""
)
op.execute(
f"""
UPDATE {DEFINITIONS} d
SET latest_published_version_no = 1,
current_version_no = 1
WHERE NOT EXISTS (
SELECT 1 FROM {VERSIONS} v
WHERE v.definition_id = d.id AND v.version_no > 1
)
AND EXISTS (
SELECT 1 FROM {VERSIONS} v WHERE v.definition_id = d.id AND v.version_no = 1
)
AND (d.latest_published_version_no IS NULL OR d.current_version_no IS NULL)
"""
)
# Any remaining gaps (e.g. latest set but current still null after inserts).
op.execute(
f"""
UPDATE {DEFINITIONS}
SET current_version_no = COALESCE(current_version_no, latest_published_version_no, 1)
WHERE current_version_no IS NULL
"""
)
finally:
op.execute(f"ALTER TABLE {VERSIONS} FORCE ROW LEVEL SECURITY")
op.execute(f"ALTER TABLE {DEFINITIONS} FORCE ROW LEVEL SECURITY")
def downgrade() -> None:
op.drop_constraint("ck_query_definitions_current_version", DEFINITIONS, type_="check")
op.drop_column(DEFINITIONS, "current_version_no")
@@ -0,0 +1,90 @@
"""Re-backfill current_version_no under FORCE ROW LEVEL SECURITY.
Revision ID: 20261118_0009
Revises: 20261118_0008
Create Date: 2026-11-18
0008 added the column but migrator updates/inserts saw zero rows or were
blocked because query_definitions / query_versions use FORCE ROW LEVEL
SECURITY. Temporarily lift FORCE on both, backfill, then restore.
"""
from __future__ import annotations
from typing import Sequence, Union
from alembic import op
revision: str = "20261118_0009"
down_revision: Union[str, None] = "20261118_0008"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
DEFINITIONS = "query_definitions"
VERSIONS = "query_versions"
def upgrade() -> None:
op.execute(f"ALTER TABLE {DEFINITIONS} NO FORCE ROW LEVEL SECURITY")
op.execute(f"ALTER TABLE {VERSIONS} NO FORCE ROW LEVEL SECURITY")
try:
op.execute(
f"""
UPDATE {DEFINITIONS}
SET current_version_no = latest_published_version_no
WHERE latest_published_version_no IS NOT NULL
AND current_version_no IS NULL
"""
)
op.execute(
f"""
INSERT INTO {VERSIONS} (
id, tenant_id, definition_id, version_no,
sql_template, param_schema, output_schema, allowed_identifiers,
timeout_ms, max_rows, published_at, published_by
)
SELECT
gen_random_uuid(),
d.tenant_id,
d.id,
1,
d.draft_sql_template,
d.draft_param_schema,
d.draft_output_schema,
d.draft_allowed_identifiers,
d.draft_timeout_ms,
d.draft_max_rows,
COALESCE(d.updated_at, d.created_at, now()),
'migration:20261118_0009'
FROM {DEFINITIONS} d
WHERE NOT EXISTS (
SELECT 1 FROM {VERSIONS} v WHERE v.definition_id = d.id
)
"""
)
op.execute(
f"""
UPDATE {DEFINITIONS} d
SET latest_published_version_no = COALESCE(latest_published_version_no, 1),
current_version_no = COALESCE(current_version_no, 1)
WHERE EXISTS (
SELECT 1 FROM {VERSIONS} v WHERE v.definition_id = d.id AND v.version_no = 1
)
AND current_version_no IS NULL
"""
)
op.execute(
f"""
UPDATE {DEFINITIONS}
SET current_version_no = COALESCE(current_version_no, latest_published_version_no, 1)
WHERE current_version_no IS NULL
"""
)
finally:
op.execute(f"ALTER TABLE {VERSIONS} FORCE ROW LEVEL SECURITY")
op.execute(f"ALTER TABLE {DEFINITIONS} FORCE ROW LEVEL SECURITY")
def downgrade() -> None:
# Data backfill only; nothing to reverse safely.
pass
+244
View File
@@ -0,0 +1,244 @@
"""Seed a local M04 demo: source table + datasource + parameterized query.
Loads secrets only from the layered env (.env.local). Safe to re-run: replaces the
demo table rows and reuses the named datasource / query when they already exist.
Does not print passwords or connection strings.
"""
from __future__ import annotations
import sys
import psycopg
from watchman.core.config import get_settings, merge_layered_env, reload_settings
from watchman.core.db import session_scope
from watchman.services import datasources as ds_service
from watchman.services import queries as q_service
DS_NAME = "演示工艺库"
QUERY_NAME = "按产线查工艺读数"
QUERY_OPTIONAL_NAME = "工艺读数(产线可选)"
TABLE = "wm_demo_process_readings"
SQL = f"""\
SELECT line_code, lot_no, metric, reading_value, sampled_at
FROM {TABLE}
WHERE line_code = :line_code
ORDER BY sampled_at DESC
"""
# Optional filter: omit line_code → all rows; supply it → filter that line.
# Cast is required on PostgreSQL so a NULL bind still has a known type (avoids SQLSTATE 42P08).
SQL_OPTIONAL = f"""\
SELECT line_code, lot_no, metric, reading_value, sampled_at
FROM {TABLE}
WHERE (CAST(:line_code AS text) IS NULL OR line_code = CAST(:line_code AS text))
ORDER BY line_code, sampled_at DESC
"""
PARAM_SCHEMA = [
{"name": "line_code", "type": "string", "required": True},
]
PARAM_SCHEMA_OPTIONAL = [
{"name": "line_code", "type": "string", "required": False},
]
OUTPUT_SCHEMA = [
{"name": "line_code", "type": "string"},
{"name": "lot_no", "type": "string"},
{"name": "metric", "type": "string"},
{"name": "reading_value", "type": "number"},
{"name": "sampled_at", "type": "datetime"},
]
def _require_pg(env: dict[str, str]) -> dict[str, str]:
keys = ("HOST", "PORT", "USER", "PASSWORD", "DATABASE")
missing = [k for k in keys if not env.get(f"WATCHMAN_TEST_PG_{k}")]
if missing:
raise SystemExit(f"missing WATCHMAN_TEST_PG_* keys: {', '.join(missing)}")
return {k: env[f"WATCHMAN_TEST_PG_{k}"] for k in keys}
def seed_source_table(pg: dict[str, str]) -> None:
conn = psycopg.connect(
host=pg["HOST"],
port=int(pg["PORT"]),
user=pg["USER"],
password=pg["PASSWORD"],
dbname=pg["DATABASE"],
connect_timeout=5,
)
try:
with conn.cursor() as cur:
cur.execute(
f"""
CREATE TABLE IF NOT EXISTS {TABLE} (
id bigserial PRIMARY KEY,
line_code text NOT NULL,
lot_no text NOT NULL,
metric text NOT NULL,
reading_value double precision NOT NULL,
sampled_at timestamptz NOT NULL
)
"""
)
cur.execute(f"DELETE FROM {TABLE}")
cur.execute(
f"""
INSERT INTO {TABLE} (line_code, lot_no, metric, reading_value, sampled_at)
VALUES
('L1', 'LOT-1001', 'temp_c', 86.5, '2026-11-18T02:00:00+00'),
('L1', 'LOT-1001', 'pressure_kpa', 101.2, '2026-11-18T02:01:00+00'),
('L1', 'LOT-1002', 'temp_c', 91.0, '2026-11-18T02:05:00+00'),
('L2', 'LOT-2001', 'temp_c', 72.3, '2026-11-18T02:10:00+00'),
('L2', 'LOT-2001', 'pressure_kpa', 98.0, '2026-11-18T02:11:00+00'),
('L3', 'LOT-3001', 'temp_c', 65.0, '2026-11-18T02:20:00+00')
"""
)
conn.commit()
finally:
conn.close()
print(f"source table ready: {TABLE} (6 rows)")
def ensure_datasource(pg: dict[str, str]) -> str:
with session_scope() as session:
existing = next((r for r in ds_service.list_datasources(session) if r.name == DS_NAME), None)
if existing is None:
row = ds_service.create_datasource(
session,
name=DS_NAME,
description="M04 本地演示源:工艺读数表(合成数据)",
kind="database",
engine="postgresql",
host=pg["HOST"],
port=int(pg["PORT"]),
database_name=pg["DATABASE"],
username=pg["USER"],
password=pg["PASSWORD"],
read_only_intent=True,
)
session.commit()
print(f"datasource created: {DS_NAME} id={row.id}")
return str(row.id)
ds_service.update_datasource(
session,
str(existing.id),
{
"description": "M04 本地演示源:工艺读数表(合成数据)",
"kind": "database",
"engine": "postgresql",
"host": pg["HOST"],
"port": int(pg["PORT"]),
"database_name": pg["DATABASE"],
"username": pg["USER"],
"password": pg["PASSWORD"],
},
)
if not existing.enabled:
ds_service.enable_datasource(session, str(existing.id))
session.commit()
print(f"datasource updated: {DS_NAME} id={existing.id}")
return str(existing.id)
def ensure_query(
datasource_id: str,
*,
name: str,
description: str,
sql_template: str,
param_schema: list[dict],
) -> str:
with session_scope() as session:
existing = next((r for r in q_service.list_queries(session) if r.name == name), None)
fields = {
"description": description,
"datasource_id": datasource_id,
"sql_template": sql_template,
"param_schema": param_schema,
"output_schema": OUTPUT_SCHEMA,
"allowed_identifiers": [],
"timeout_ms": 10000,
"max_rows": 100,
}
if existing is None:
row = q_service.create_query(
session, name=name, published_by="seed_m04_demo", **fields
)
session.commit()
qid = str(row.id)
print(f"query created: {name} id={qid} current=v{row.current_version_no}")
else:
meta = {
"description": fields["description"],
"datasource_id": fields["datasource_id"],
}
q_service.update_query(session, str(existing.id), meta)
version = q_service.save_as_version(
session,
str(existing.id),
{
"sql_template": fields["sql_template"],
"param_schema": fields["param_schema"],
"output_schema": fields["output_schema"],
"allowed_identifiers": fields["allowed_identifiers"],
"timeout_ms": fields["timeout_ms"],
"max_rows": fields["max_rows"],
},
published_by="seed_m04_demo",
)
if not existing.enabled:
q_service.enable_query(session, str(existing.id))
session.commit()
qid = str(existing.id)
print(f"query updated: {name} id={qid} current=v{version.version_no}")
return qid
def preview(query_id: str, params: dict) -> None:
with session_scope() as session:
result = q_service.preview_current(session, query_id, params)
session.commit()
status = result.get("status")
rows = result.get("rows") or []
print(f"preview params={params!r} status={status} row_count={result.get('row_count', len(rows))}")
for row in rows[:5]:
print(f" {row}")
def main() -> int:
reload_settings()
env = merge_layered_env()
pg = _require_pg(env)
settings = get_settings()
print(f"tenant={settings.tenant_id} source_db={pg['DATABASE']}@{pg['HOST']}:{pg['PORT']}")
seed_source_table(pg)
ds_id = ensure_datasource(pg)
qid = ensure_query(
ds_id,
name=QUERY_NAME,
description="按产线过滤工艺读数;试跑时传入 line_code=L1 / L2 / L3(必填)",
sql_template=SQL,
param_schema=PARAM_SCHEMA,
)
qid_opt = ensure_query(
ds_id,
name=QUERY_OPTIONAL_NAME,
description="line_code 非必填:留空查全部产线;填写则只查该产线(L1 / L2 / L3)",
sql_template=SQL_OPTIONAL,
param_schema=PARAM_SCHEMA_OPTIONAL,
)
preview(qid, {"line_code": "L1"})
preview(qid_opt, {})
preview(qid_opt, {"line_code": "L2"})
print(f"open required: http://127.0.0.1:5173/#/queries/{qid}")
print(f"open optional: http://127.0.0.1:5173/#/queries/{qid_opt}")
return 0
if __name__ == "__main__":
sys.exit(main())
+2 -1
View File
@@ -10,7 +10,7 @@ from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
from watchman.api.routes import auth, datasources, health, platform
from watchman.api.routes import auth, datasources, health, platform, queries
from watchman.core.config import ensure_runtime_config, get_settings, is_non_production
from watchman.core.errors import AppError, ValidationError
from watchman.core.request_id import REQUEST_ID_HEADER, resolve_request_id
@@ -78,6 +78,7 @@ def create_app(*, validate_runtime: bool = True) -> FastAPI:
app.include_router(auth.router)
app.include_router(platform.router)
app.include_router(datasources.router)
app.include_router(queries.router)
@app.exception_handler(AppError)
async def app_error_handler(request: Request, exc: AppError) -> JSONResponse:
@@ -105,12 +105,46 @@ def _ok(request: Request, data: Any) -> JSONResponse:
def list_datasources(
request: Request,
usable: bool = False,
name: str | None = None,
engine: str | None = None,
enabled: bool | None = None,
sort_by: str = "created_at",
sort_order: str = "asc",
page: int = 1,
page_size: int = 20,
_: None = Depends(require_datasource_reader),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""List the server tenant's datasources; usable=true keeps enabled, circuit-closed ones."""
rows = service.list_datasources(session, usable_only=usable)
data = {"items": [service.to_public(row) for row in rows]}
"""List datasources.
usable=true returns the complete option list (enabled + circuit closed) for dropdowns.
Otherwise filters, sorts and pages in SQL for the console table.
"""
if usable:
rows = service.list_datasources(session, usable_only=True)
data = {
"items": [service.to_public(row) for row in rows],
"total": len(rows),
"page": 1,
"page_size": len(rows) or page_size,
}
else:
result = service.search_datasources(
session,
name=name,
engine=engine,
enabled=enabled,
sort_by=sort_by,
sort_order=sort_order,
page=page,
page_size=page_size,
)
data = {
"items": [service.to_public(row) for row in result["items"]],
"total": result["total"],
"page": result["page"],
"page_size": result["page_size"],
}
# An elapsed cooldown closes the circuit while listing; persist that.
session.commit()
return _ok(request, data)
@@ -240,5 +274,5 @@ def get_datasource_references(
_: None = Depends(require_datasource_reader),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Return what references this datasource. Nothing does yet, so items is empty."""
"""Return what references this datasource: the query definitions bound to it."""
return _ok(request, service.list_references(session, datasource_id))
@@ -0,0 +1,301 @@
"""Query definition routes under /queries.
Why: lets the console create definitions with immutable v1, save further versions, activate
a current version, and trial-run current or a chosen version (D26).
Boundary: request models forbid unknown fields, so a caller can never send tenant_id,
version_no, published_by or current_version_no; there is deliberately no route that updates
or deletes a version. Business rules live in watchman.services.queries.
Depends on the query service and the four query permission dependencies.
"""
from __future__ import annotations
from typing import Annotated, Any
from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict, Field, StringConstraints
from sqlalchemy.orm import Session
from watchman.auth.principal import (
require_query_previewer,
require_query_publisher,
require_query_reader,
require_query_writer,
)
from watchman.core.db import get_db_session
from watchman.core.response import success_body
from watchman.models.query import DEFAULT_MAX_ROWS, DEFAULT_TIMEOUT_MS
from watchman.services import queries as service
router = APIRouter(prefix="/queries", tags=["queries"])
Name = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=128)]
Description = Annotated[str, StringConstraints(max_length=2000)]
# Not stripped: whitespace inside SQL is content. Blank templates are refused by the service.
SqlTemplate = Annotated[str, StringConstraints(max_length=100000)]
# A value above the server cap is capped by the service; below 1 or a non-int is a 40000.
Limit = Annotated[int, Field(ge=1, strict=True)]
class QueryCreate(BaseModel):
"""Create body. Unknown fields such as tenant_id or enabled are rejected with 40000."""
model_config = ConfigDict(extra="forbid")
name: Name
description: Description | None = None
datasource_id: str
sql_template: SqlTemplate
param_schema: list[dict[str, Any]] = Field(default_factory=list)
output_schema: list[dict[str, Any]] = Field(default_factory=list)
allowed_identifiers: list[str] = Field(default_factory=list)
timeout_ms: Limit = DEFAULT_TIMEOUT_MS
max_rows: Limit = DEFAULT_MAX_ROWS
class QueryUpdate(BaseModel):
"""Metadata-only PATCH. Content must be saved as a new version (D26)."""
model_config = ConfigDict(extra="forbid")
name: Name | None = None
description: Description | None = None
datasource_id: str | None = None
class VersionCreate(BaseModel):
"""Body for saving a new immutable version that becomes current."""
model_config = ConfigDict(extra="forbid")
sql_template: SqlTemplate
param_schema: list[dict[str, Any]] = Field(default_factory=list)
output_schema: list[dict[str, Any]] = Field(default_factory=list)
allowed_identifiers: list[str] = Field(default_factory=list)
timeout_ms: Limit = DEFAULT_TIMEOUT_MS
max_rows: Limit = DEFAULT_MAX_ROWS
class EmptyBody(BaseModel):
"""Optional body for enable / disable / activate; it has no fields."""
model_config = ConfigDict(extra="forbid")
class PreviewBody(BaseModel):
"""Parameter values for a trial run. Nothing else (no SQL, no datasource) can be sent."""
model_config = ConfigDict(extra="forbid")
params: dict[str, Any] = Field(default_factory=dict)
def _ok(request: Request, data: Any) -> JSONResponse:
return JSONResponse(content=success_body(data, request_id=request.state.request_id))
@router.get("")
def list_queries(
request: Request,
enabled: bool | None = None,
name: str | None = None,
datasource_id: str | None = None,
sort_by: str = "updated_at",
sort_order: str = "desc",
page: int = 1,
page_size: int = 20,
_: None = Depends(require_query_reader),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""List query definitions with optional filters; sort and page in SQL."""
result = service.search_queries(
session,
enabled=enabled,
name=name,
datasource_id=datasource_id,
sort_by=sort_by,
sort_order=sort_order,
page=page,
page_size=page_size,
)
return _ok(
request,
{
"items": [service.summary_public(row) for row in result["items"]],
"total": result["total"],
"page": result["page"],
"page_size": result["page_size"],
},
)
@router.post("")
def create_query(
request: Request,
body: QueryCreate,
login_name: str = Depends(require_query_publisher),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Create an enabled definition with immutable v1 as current."""
# Creating v1 is a publish-class write (D26); publisher dependency also yields login_name.
row = service.create_query(session, published_by=login_name, **body.model_dump())
data = service.to_public(row)
session.commit()
return _ok(request, data)
@router.get("/{query_id}")
def get_query(
request: Request,
query_id: str,
_: None = Depends(require_query_reader),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Return one definition with current content and version pointers."""
return _ok(request, service.to_public(service.get_query(session, query_id)))
@router.patch("/{query_id}")
def update_query(
request: Request,
query_id: str,
body: QueryUpdate,
_: None = Depends(require_query_writer),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Update metadata only. SQL content is saved via POST .../versions."""
row = service.update_query(session, query_id, body.model_dump(exclude_unset=True))
data = service.to_public(row)
session.commit()
return _ok(request, data)
@router.post("/{query_id}/disable")
def disable_query(
request: Request,
query_id: str,
body: EmptyBody | None = None,
_: None = Depends(require_query_writer),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Disable a definition. It stays readable and cannot be previewed."""
row = service.disable_query(session, query_id)
data = service.to_public(row)
session.commit()
return _ok(request, data)
@router.post("/{query_id}/enable")
def enable_query(
request: Request,
query_id: str,
body: EmptyBody | None = None,
_: None = Depends(require_query_writer),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Enable a definition again."""
row = service.enable_query(session, query_id)
data = service.to_public(row)
session.commit()
return _ok(request, data)
@router.get("/{query_id}/versions")
def list_query_versions(
request: Request,
query_id: str,
_: None = Depends(require_query_reader),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""List version summaries, newest first."""
rows = service.list_versions(session, query_id)
return _ok(
request,
{"id": query_id, "items": [service.version_summary(row) for row in rows]},
)
@router.post("/{query_id}/versions")
def save_query_version(
request: Request,
query_id: str,
body: VersionCreate,
login_name: str = Depends(require_query_publisher),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Save content as the next immutable version and make it current (D26)."""
version = service.save_as_version(
session, query_id, body.model_dump(), published_by=login_name
)
data = service.version_public(version)
session.commit()
return _ok(request, data)
@router.get("/{query_id}/versions/{version_no}")
def get_query_version(
request: Request,
query_id: str,
version_no: int,
_: None = Depends(require_query_reader),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Return one frozen version. Read-only: no route can change it."""
return _ok(request, service.version_public(service.get_version(session, query_id, version_no)))
@router.post("/{query_id}/versions/{version_no}/activate")
def activate_query_version(
request: Request,
query_id: str,
version_no: int,
body: EmptyBody | None = None,
_: None = Depends(require_query_publisher),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Set an existing version as the current active version."""
row = service.activate_version(session, query_id, version_no)
data = service.to_public(row)
session.commit()
return _ok(request, data)
@router.post("/{query_id}/preview")
def preview_query_current(
request: Request,
query_id: str,
body: PreviewBody | None = None,
_: None = Depends(require_query_previewer),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Trial-run the current active version. Outcome is only in the response."""
data = service.preview_current(session, query_id, (body or PreviewBody()).params)
session.commit()
return _ok(request, data)
@router.post("/{query_id}/versions/{version_no}/preview")
def preview_query_version(
request: Request,
query_id: str,
version_no: int,
body: PreviewBody | None = None,
_: None = Depends(require_query_previewer),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Trial-run a frozen version. The outcome is only in the response; nothing is stored."""
data = service.preview_version(session, query_id, version_no, (body or PreviewBody()).params)
session.commit()
return _ok(request, data)
@router.get("/{query_id}/references")
def get_query_references(
request: Request,
query_id: str,
_: None = Depends(require_query_reader),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Return what references this query. No scenario exists yet, so items is empty."""
return _ok(request, service.list_references(session, query_id))
+30 -1
View File
@@ -1,7 +1,7 @@
"""Role checks for the Watchman permission nodes.
Decides enter, platform write, object read, and the three datasource nodes (read,
write, test) from Casdoor role names.
write, test) and the four query nodes (read, write, publish, preview) from Casdoor role names.
Depends on semantic errors only; it does not call Casdoor or open a session.
"""
@@ -17,6 +17,11 @@ DATASOURCE_READ_NODE = "perm:data:emp:watchman.datasource.read"
DATASOURCE_WRITE_NODE = "perm:data:emp:watchman.datasource.write"
DATASOURCE_TEST_NODE = "perm:data:emp:watchman.datasource.test"
QUERY_READ_NODE = "perm:data:emp:watchman.query.read"
QUERY_WRITE_NODE = "perm:data:emp:watchman.query.write"
QUERY_PUBLISH_NODE = "perm:data:emp:watchman.query.publish"
QUERY_PREVIEW_NODE = "perm:data:emp:watchman.query.preview"
ROLE_ADMIN = "watchman-admin"
ROLE_OPERATOR = "watchman-operator"
ROLE_VIEWER = "watchman-viewer"
@@ -65,6 +70,30 @@ def require_datasource_test(role_names: list[str]) -> None:
raise ForbiddenError(permission_node=DATASOURCE_TEST_NODE)
def require_query_read(role_names: list[str]) -> None:
"""Allow query list, detail, versions and references only for watchman-admin."""
if ROLE_ADMIN not in role_names:
raise ForbiddenError(permission_node=QUERY_READ_NODE)
def require_query_write(role_names: list[str]) -> None:
"""Allow query create, update, enable and disable only for watchman-admin."""
if ROLE_ADMIN not in role_names:
raise ForbiddenError(permission_node=QUERY_WRITE_NODE)
def require_query_publish(role_names: list[str]) -> None:
"""Allow publishing an immutable query version only for watchman-admin."""
if ROLE_ADMIN not in role_names:
raise ForbiddenError(permission_node=QUERY_PUBLISH_NODE)
def require_query_preview(role_names: list[str]) -> None:
"""Allow a draft or version preview run only for watchman-admin."""
if ROLE_ADMIN not in role_names:
raise ForbiddenError(permission_node=QUERY_PREVIEW_NODE)
def require_object_access(role_names: list[str], object_id: str) -> None:
"""Reject every object id until a later module grants row access.
@@ -19,6 +19,10 @@ from watchman.auth.access import (
require_datasource_test,
require_datasource_write,
require_platform_write,
require_query_preview,
require_query_publish,
require_query_read,
require_query_write,
)
from watchman.auth.sessions import (
SESSION_COOKIE_NAME,
@@ -124,13 +128,13 @@ def require_platform_writer(
require_platform_write(roles)
def _load_session_roles(
def _load_session(
request: Request,
session_token: str | None,
sessions: SessionStore,
directory: RoleDirectory,
) -> list[str]:
"""Return fresh role names for the caller's session, or raise 41000 / 503.
) -> tuple[str, list[str]]:
"""Return (login_name, fresh role names) for the caller's session, or raise 41000 / 503.
Same session and freshness rules as require_platform_writer: a stale snapshot is
reloaded from Casdoor and, if that fails, the old roles are not used.
@@ -146,7 +150,17 @@ def _load_session_roles(
if now - row.role_checked_at >= ROLE_FRESHNESS:
roles = directory.lookup_roles(login_name=row.login_name)
sessions.update_roles(token_hash=row.token_hash, role_names=roles, now=now)
return roles
return row.login_name, roles
def _load_session_roles(
request: Request,
session_token: str | None,
sessions: SessionStore,
directory: RoleDirectory,
) -> list[str]:
"""Return fresh role names for the caller's session, or raise 41000 / 503."""
return _load_session(request, session_token, sessions, directory)[1]
def require_datasource_reader(
@@ -177,3 +191,45 @@ def require_datasource_tester(
) -> None:
"""Reject a connection test unless the session is watchman-admin."""
require_datasource_test(_load_session_roles(request, session_token, sessions, directory))
def require_query_reader(
request: Request,
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
sessions: SessionStore = Depends(get_session_store),
directory: RoleDirectory = Depends(get_role_directory),
) -> None:
"""Reject query list, detail, version and reference reads unless the session is admin."""
require_query_read(_load_session_roles(request, session_token, sessions, directory))
def require_query_writer(
request: Request,
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
sessions: SessionStore = Depends(get_session_store),
directory: RoleDirectory = Depends(get_role_directory),
) -> None:
"""Reject query create, update, enable and disable unless the session is admin."""
require_query_write(_load_session_roles(request, session_token, sessions, directory))
def require_query_publisher(
request: Request,
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
sessions: SessionStore = Depends(get_session_store),
directory: RoleDirectory = Depends(get_role_directory),
) -> str:
"""Reject a publish unless the session is admin; return the login name to record."""
login_name, roles = _load_session(request, session_token, sessions, directory)
require_query_publish(roles)
return login_name
def require_query_previewer(
request: Request,
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
sessions: SessionStore = Depends(get_session_store),
directory: RoleDirectory = Depends(get_role_directory),
) -> None:
"""Reject a draft or version preview unless the session is admin."""
require_query_preview(_load_session_roles(request, session_token, sessions, directory))
@@ -3,5 +3,13 @@
from watchman.models.auth_session import AuthSession
from watchman.models.datasource import DataSource
from watchman.models.platform import AuditEvent, RunRecord
from watchman.models.query import QueryDefinition, QueryVersion
__all__ = ["AuthSession", "AuditEvent", "DataSource", "RunRecord"]
__all__ = [
"AuthSession",
"AuditEvent",
"DataSource",
"QueryDefinition",
"QueryVersion",
"RunRecord",
]
@@ -0,0 +1,170 @@
"""Tenant-scoped query drafts and immutable published query versions.
Boundary: persistence only. A QueryDefinition holds the mutable draft; a QueryVersion is a
frozen snapshot that must never be edited in place (enforced by the service helper in
`watchman.services.query_versions`, not by this module). No SQL execution and no datasource
connection logic live here.
Depends on SQLAlchemy, the shared Watchman declarative base, and the data_sources table.
"""
from __future__ import annotations
import uuid
from datetime import datetime
from typing import Any
from sqlalchemy import (
Boolean,
CheckConstraint,
DateTime,
ForeignKey,
Integer,
String,
Text,
UniqueConstraint,
func,
text,
)
from sqlalchemy.dialects.postgresql import JSONB, UUID
from sqlalchemy.orm import Mapped, mapped_column
from watchman.models.base import Base
DEFAULT_TIMEOUT_MS = 10000
DEFAULT_MAX_ROWS = 100
MAX_TIMEOUT_MS = 300000
MAX_ROWS_LIMIT = 10000
# Columns that make up a published version's content; frozen once the row exists.
VERSION_CONTENT_COLUMNS = frozenset(
{
"sql_template",
"param_schema",
"output_schema",
"allowed_identifiers",
"timeout_ms",
"max_rows",
}
)
class QueryDefinition(Base):
"""A query definition with mirrored draft_* columns and current/latest version pointers.
D26: callers treat versions as the source of truth; draft_* mirrors the current version
for transitional internals and is not exposed as an editable draft API.
"""
__tablename__ = "query_definitions"
__table_args__ = (
UniqueConstraint("tenant_id", "name", name="uq_query_definitions_tenant_name"),
CheckConstraint(
"draft_timeout_ms BETWEEN 1 AND 300000", name="ck_query_definitions_timeout"
),
CheckConstraint(
"draft_max_rows BETWEEN 1 AND 10000", name="ck_query_definitions_max_rows"
),
CheckConstraint(
"latest_published_version_no IS NULL OR latest_published_version_no >= 1",
name="ck_query_definitions_latest_version",
),
CheckConstraint(
"current_version_no IS NULL OR current_version_no >= 1",
name="ck_query_definitions_current_version",
),
)
id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
primary_key=True,
server_default=text("gen_random_uuid()"),
)
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
name: Mapped[str] = mapped_column(String(128), nullable=False)
description: Mapped[str | None] = mapped_column(Text, nullable=True)
# RESTRICT: a datasource referenced by a query cannot be deleted out from under it.
datasource_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
ForeignKey("data_sources.id", ondelete="RESTRICT"),
nullable=False,
)
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
draft_sql_template: Mapped[str] = mapped_column(Text, nullable=False)
draft_param_schema: Mapped[list[Any]] = mapped_column(
JSONB, nullable=False, default=list, server_default=text("'[]'::jsonb")
)
draft_output_schema: Mapped[list[Any]] = mapped_column(
JSONB, nullable=False, default=list, server_default=text("'[]'::jsonb")
)
# Whitelist for identifiers that cannot be bound as parameters (tables, columns).
draft_allowed_identifiers: Mapped[list[Any]] = mapped_column(
JSONB, nullable=False, default=list, server_default=text("'[]'::jsonb")
)
draft_timeout_ms: Mapped[int] = mapped_column(
Integer,
nullable=False,
default=DEFAULT_TIMEOUT_MS,
server_default=text(str(DEFAULT_TIMEOUT_MS)),
)
draft_max_rows: Mapped[int] = mapped_column(
Integer,
nullable=False,
default=DEFAULT_MAX_ROWS,
server_default=text(str(DEFAULT_MAX_ROWS)),
)
latest_published_version_no: Mapped[int | None] = mapped_column(Integer, nullable=True)
# Active version for future rules/schedules and default preview (D26).
current_version_no: Mapped[int | None] = mapped_column(Integer, nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now()
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now()
)
def __repr__(self) -> str:
return (
f"QueryDefinition(id={self.id!s}, tenant_id={self.tenant_id!r}, "
f"name={self.name!r})"
)
class QueryVersion(Base):
"""An immutable published snapshot of a query definition; there is no updated_at."""
__tablename__ = "query_versions"
__table_args__ = (
UniqueConstraint("definition_id", "version_no", name="uq_query_versions_def_version"),
CheckConstraint("version_no >= 1", name="ck_query_versions_version_no"),
CheckConstraint("timeout_ms BETWEEN 1 AND 300000", name="ck_query_versions_timeout"),
CheckConstraint("max_rows BETWEEN 1 AND 10000", name="ck_query_versions_max_rows"),
)
id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
primary_key=True,
server_default=text("gen_random_uuid()"),
)
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
definition_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
ForeignKey("query_definitions.id", ondelete="RESTRICT"),
nullable=False,
)
version_no: Mapped[int] = mapped_column(Integer, nullable=False)
sql_template: Mapped[str] = mapped_column(Text, nullable=False)
param_schema: Mapped[list[Any]] = mapped_column(JSONB, nullable=False)
output_schema: Mapped[list[Any]] = mapped_column(JSONB, nullable=False)
allowed_identifiers: Mapped[list[Any]] = mapped_column(JSONB, nullable=False)
timeout_ms: Mapped[int] = mapped_column(Integer, nullable=False)
max_rows: Mapped[int] = mapped_column(Integer, nullable=False)
published_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now()
)
published_by: Mapped[str | None] = mapped_column(String(128), nullable=True)
def __repr__(self) -> str:
return (
f"QueryVersion(id={self.id!s}, definition_id={self.definition_id!s}, "
f"version_no={self.version_no})"
)
@@ -0,0 +1,15 @@
"""Read-only parameterized query execution against saved datasources.
Boundary: executes user SQL templates once and classifies the outcome (success / empty /
illegal_type / failure). It does not persist query definitions or versions, does not create
alarms, rules or notifications, and never bypasses the datasource usability check and
circuit. Template preparation (bound parameters, whitelisted identifiers) is pure and
connection-free; only `run_query` touches a datasource.
Depends on watchman.services.datasources and watchman.datasources connectors.
"""
from watchman.queries.execute import run_query
from watchman.queries.result import QueryRunResult
from watchman.queries.template import PreparedQuery, prepare_query
__all__ = ["PreparedQuery", "QueryRunResult", "prepare_query", "run_query"]
@@ -0,0 +1,236 @@
"""Per-engine execution of one prepared statement on a short-lived connection.
Boundary: opens one connection, runs exactly one statement in a read-only transaction where
the engine supports it (PostgreSQL, MySQL; SQL Server has no session read-only mode, so it is
not supported here at all), fetches at most `limit` rows and closes. It classifies failures
but does not persist anything, decrypt secrets, or look at the data. Driver messages are
never copied into exceptions: only a category/kind and, for PostgreSQL, the 5-char SQLSTATE.
Connect-failure classification reuses the probe's rules so both agree on what a refused,
rejected or unauthenticated connection is.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import Any
import psycopg
import pymysql
from watchman.datasources import ProbeCategory, ProbeTarget, UnsupportedDataSourceError
from watchman.datasources.probe import (
_MYSQL_AUTH_CODES,
_MYSQL_SERVER_ERROR_LIMIT,
_chain_has_timeout,
_classify_after_failure,
_pg_connect,
_pg_is_auth_failure,
)
# MySQL: ER_QUERY_TIMEOUT (MAX_EXECUTION_TIME exceeded).
_MYSQL_QUERY_TIMEOUT = 3024
@dataclass(frozen=True)
class FetchResult:
columns: list[str]
rows: list[tuple[Any, ...]]
class ConnectFailure(Exception):
"""No usable connection was established. Counts against the datasource circuit."""
def __init__(self, category: ProbeCategory) -> None:
super().__init__(category.value)
self.category = category
class QueryFailure(Exception):
"""The statement did not complete on an established connection.
category is set only when the failure is clearly connectivity (connection lost
mid-query); then it counts against the circuit. A slow or broken statement does not.
"""
def __init__(
self,
kind: str,
*,
category: ProbeCategory | None = None,
details: dict[str, Any] | None = None,
) -> None:
super().__init__(kind)
self.kind = kind # "timeout" | "unreachable" | "sql_error"
self.category = category
self.details = details or {}
def fetch_rows(
target: ProbeTarget,
sql: str,
params: dict[str, Any] | None,
*,
timeout_ms: int,
limit: int,
connect_timeout: float,
) -> FetchResult:
"""Run `sql` with bound `params` and return at most `limit` rows.
Raises UnsupportedDataSourceError (nothing opened), ConnectFailure or QueryFailure.
"""
runner = _RUNNERS.get(target.engine) if target.kind == "database" else None
if runner is None:
raise UnsupportedDataSourceError()
return runner(target, sql, params, timeout_ms, limit, connect_timeout)
# --- PostgreSQL -----------------------------------------------------------------------
def _run_postgresql(
target: ProbeTarget,
sql: str,
params: dict[str, Any] | None,
timeout_ms: int,
limit: int,
connect_timeout: float,
) -> FetchResult:
try:
conn = _pg_connect(target, connect_timeout, "UTF8")
except psycopg.Error as exc:
sqlstate = getattr(exc, "sqlstate", None) or ""
if sqlstate.startswith("28"):
raise ConnectFailure(ProbeCategory.AUTH_FAILED) from None
timed_out = isinstance(exc, psycopg.errors.ConnectionTimeout) or _chain_has_timeout(exc)
category = _classify_after_failure(
target,
connect_timeout,
timed_out,
lambda: _pg_is_auth_failure(exc, target, connect_timeout),
)
raise ConnectFailure(category) from None
except Exception: # noqa: BLE001
raise ConnectFailure(ProbeCategory.UNREACHABLE) from None
try:
# READ ONLY transaction (BEGIN READ ONLY), statement_timeout scoped to it.
conn.autocommit = False
conn.read_only = True
with conn.cursor() as cur:
cur.execute(f"SET LOCAL statement_timeout = {int(timeout_ms)}")
cur.execute(sql, params)
if cur.description is None:
raise QueryFailure("sql_error", details={"reason": "no_result_set"})
columns = [column.name for column in cur.description]
rows = cur.fetchmany(limit)
return FetchResult(columns=columns, rows=[tuple(r) for r in rows])
except QueryFailure:
raise
except psycopg.errors.QueryCanceled:
raise QueryFailure("timeout") from None
except psycopg.OperationalError as exc:
sqlstate = getattr(exc, "sqlstate", None) or ""
if not sqlstate or sqlstate.startswith("08"):
raise QueryFailure("unreachable", category=ProbeCategory.UNREACHABLE) from None
raise QueryFailure("sql_error", details={"sqlstate": sqlstate}) from None
except psycopg.Error as exc:
sqlstate = getattr(exc, "sqlstate", None) or ""
raise QueryFailure("sql_error", details={"sqlstate": sqlstate}) from None
finally:
_quiet(conn.rollback)
_quiet(conn.close)
# --- MySQL ----------------------------------------------------------------------------
def _mysql_code(exc: BaseException) -> int | None:
return exc.args[0] if exc.args and isinstance(exc.args[0], int) else None
def _run_mysql(
target: ProbeTarget,
sql: str,
params: dict[str, Any] | None,
timeout_ms: int,
limit: int,
connect_timeout: float,
) -> FetchResult:
try:
conn = pymysql.connect(
host=target.host,
port=target.port,
user=target.username,
password=target.password,
database=target.database,
connect_timeout=connect_timeout,
# read_timeout is the client-side cap on a running statement.
read_timeout=max(1.0, math.ceil(timeout_ms / 1000)),
write_timeout=connect_timeout,
autocommit=False,
)
except pymysql.err.MySQLError as exc:
code = _mysql_code(exc)
if code in _MYSQL_AUTH_CODES:
raise ConnectFailure(ProbeCategory.AUTH_FAILED) from None
if _chain_has_timeout(exc):
raise ConnectFailure(ProbeCategory.TIMEOUT) from None
if code is not None and code < _MYSQL_SERVER_ERROR_LIMIT:
raise ConnectFailure(ProbeCategory.REJECTED) from None
raise ConnectFailure(ProbeCategory.UNREACHABLE) from None
except OSError as exc:
raise ConnectFailure(
ProbeCategory.TIMEOUT if _chain_has_timeout(exc) else ProbeCategory.UNREACHABLE
) from None
except Exception: # noqa: BLE001
raise ConnectFailure(ProbeCategory.UNREACHABLE) from None
try:
with conn.cursor() as cur:
cur.execute("SET SESSION TRANSACTION READ ONLY")
cur.execute("START TRANSACTION READ ONLY")
try:
cur.execute(f"SET SESSION MAX_EXECUTION_TIME = {int(timeout_ms)}")
except pymysql.err.MySQLError:
pass # MariaDB / old servers: the client read_timeout still applies
cur.execute(sql, params)
if cur.description is None:
raise QueryFailure("sql_error", details={"reason": "no_result_set"})
columns = [column[0] for column in cur.description]
rows = cur.fetchmany(limit)
return FetchResult(columns=columns, rows=[tuple(r) for r in rows])
except QueryFailure:
raise
except pymysql.err.MySQLError as exc:
code = _mysql_code(exc)
if code == _MYSQL_QUERY_TIMEOUT or _chain_has_timeout(exc):
raise QueryFailure("timeout") from None
if code is not None and code >= _MYSQL_SERVER_ERROR_LIMIT:
# 2006/2013 and friends: the connection died, not the statement.
raise QueryFailure("unreachable", category=ProbeCategory.UNREACHABLE) from None
raise QueryFailure("sql_error", details={"code": code}) from None
except OSError as exc:
if _chain_has_timeout(exc):
raise QueryFailure("timeout") from None
raise QueryFailure("unreachable", category=ProbeCategory.UNREACHABLE) from None
finally:
_quiet(conn.rollback)
_quiet(conn.close)
# --- SQL Server -----------------------------------------------------------------------
# Deliberately no runner: SQL Server has no server-enforced read-only session in this stack,
# so user templates are never executed on it (see execute.run_query). fetch_rows raises
# UnsupportedDataSourceError for it, and nothing here imports pymssql.
def _quiet(call) -> None: # type: ignore[no-untyped-def]
try:
call()
except Exception: # noqa: BLE001
pass
_RUNNERS = {
"postgresql": _run_postgresql,
"mysql": _run_mysql,
}
@@ -0,0 +1,269 @@
"""Read-only parameterized query runner for usable datasources.
Boundary: executes a user template once against a saved datasource and reports the outcome.
It does not persist query definitions or results, does not create alarms or notifications,
and never connects to a datasource that M03 `assert_usable` refuses. Connection-class
failures (connect, auth, rejected, unreachable, connection lost) are counted against the
datasource circuit; a slow or invalid statement on a healthy connection is not. Password,
connection details, parameter values and result sets are never logged.
Depends on the datasource service (usability, secret, circuit accounting), the probe's
connectors, and the template/schema helpers of this package.
"""
from __future__ import annotations
import logging
import math
import uuid
from datetime import date, datetime, time
from decimal import Decimal
from typing import Any
from sqlalchemy.orm import Session
from watchman.core.config import get_settings
from watchman.core.errors import ConflictError, ValidationError
from watchman.datasources import ProbeCategory, UnsupportedDataSourceError
from watchman.models.query import MAX_ROWS_LIMIT, MAX_TIMEOUT_MS
from watchman.queries import drivers
from watchman.queries.result import (
KIND_AUTH_FAILED,
KIND_CIRCUIT_OPEN,
KIND_DISABLED,
KIND_ENGINE_READONLY_UNSUPPORTED,
KIND_LIMIT_EXCEEDED,
KIND_REJECTED,
KIND_SQL_ERROR,
KIND_TIMEOUT,
KIND_UNREACHABLE,
KIND_VALIDATION,
STATUS_EMPTY,
STATUS_ILLEGAL_TYPE,
STATUS_SUCCESS,
QueryRunResult,
failure,
)
from watchman.queries.schema import check_output_value, parse_output_schema
from watchman.queries.template import prepare_query
from watchman.services import datasources as datasource_service
logger = logging.getLogger("watchman.queries.execute")
# Fixed texts: driver messages can embed hosts, users or fragments of the statement.
_CATEGORY_KIND = {
ProbeCategory.AUTH_FAILED: KIND_AUTH_FAILED,
ProbeCategory.TIMEOUT: KIND_TIMEOUT,
ProbeCategory.UNREACHABLE: KIND_UNREACHABLE,
ProbeCategory.REJECTED: KIND_REJECTED,
}
_MESSAGES = {
KIND_AUTH_FAILED: "data source authentication failed",
KIND_TIMEOUT: "query timed out",
KIND_UNREACHABLE: "data source unreachable",
KIND_REJECTED: "data source rejected the connection",
KIND_SQL_ERROR: "query failed",
KIND_LIMIT_EXCEEDED: "query returned more rows than max_rows",
KIND_VALIDATION: "query template or parameters are invalid",
KIND_DISABLED: "data source is disabled",
KIND_CIRCUIT_OPEN: "data source circuit is open",
KIND_ENGINE_READONLY_UNSUPPORTED: (
"SQL Server query preview is not available until a server-enforced "
"read-only session exists"
),
}
# Engines without a server-enforced read-only session. User templates are never executed on
# them: a statement check would not be a security control. The M03 connectivity probe is
# unaffected (it runs no user SQL).
_READONLY_UNSUPPORTED_ENGINES = frozenset({"sqlserver"})
def _clamp(name: str, value: Any, maximum: int) -> int:
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
raise ValidationError(
"Invalid query limits", details={"reason": "limit_invalid", "fields": [name]}
)
return min(value, maximum) # a form value above the server cap is capped, not trusted
def _json_value(value: Any) -> Any:
"""Convert a fetched value to something json.dumps accepts."""
if value is None or isinstance(value, (str, bool, int)):
return value
if isinstance(value, float):
return value if math.isfinite(value) else None
if isinstance(value, Decimal):
return float(value) if value.is_finite() else None
if isinstance(value, (datetime, date, time)):
return value.isoformat()
if isinstance(value, (bytes, bytearray, memoryview)):
return bytes(value).hex()
return str(value)
def _type_problems(
declared: dict[str, str], columns: list[str], rows: list[tuple[Any, ...]]
) -> list[dict[str, Any]]:
"""First offending row per declared column; values are never included."""
problems: list[dict[str, Any]] = []
for index, name in enumerate(columns):
expected = declared.get(name)
if expected is None:
continue
for row_no, row in enumerate(rows):
if not check_output_value(expected, row[index]):
problems.append(
{
"field": name,
"expected": expected,
"actual": type(row[index]).__name__,
"row": row_no,
}
)
break
return problems
def run_query(
session: Session,
*,
datasource_id: str | uuid.UUID,
sql_template: str,
param_schema: Any,
output_schema: Any,
allowed_identifiers: Any,
params: Any,
timeout_ms: int,
max_rows: int,
) -> QueryRunResult:
"""Run one template read-only and classify the outcome; never raises for query problems.
Order: assert_usable (disabled/circuit_open come back as failures, no SQL, no secret
read) -> refuse engines without a server-enforced read-only session (SQL Server:
failure `engine_readonly_unsupported`, nothing opened) -> validate limits, schemas, parameters and identifiers (failure `validation`) ->
decrypt in memory, commit so no transaction spans the network call -> run with timeout
-> classify. Fetches max_rows+1 rows: one extra row is `limit_exceeded` (no rows
returned), zero is `empty`, a declared output type violated is `illegal_type`.
Unknown datasource (NotFoundError) and an unreadable stored secret propagate as the
platform's own errors. This function commits the session; connection failures are
recorded on the circuit and committed before it returns.
"""
ds_id = str(datasource_id)
try:
row = datasource_service.assert_usable(session, ds_id)
except ConflictError as exc:
reason = exc.details.get("reason")
kind = KIND_CIRCUIT_OPEN if reason == KIND_CIRCUIT_OPEN else KIND_DISABLED
extra = {k: v for k, v in exc.details.items() if k == "circuit_open_until"}
return failure(kind, _MESSAGES[kind], reason=reason, **extra)
if row.engine in _READONLY_UNSUPPORTED_ENGINES:
# Refuse before validation, secret decryption or any connection: nothing is opened.
session.commit() # persists an auto-closed circuit and ends the read transaction
logger.info(
"query run engine=%s datasource=%s status=failure kind=%s",
row.engine,
ds_id,
KIND_ENGINE_READONLY_UNSUPPORTED,
)
return failure(
KIND_ENGINE_READONLY_UNSUPPORTED,
_MESSAGES[KIND_ENGINE_READONLY_UNSUPPORTED],
reason=KIND_ENGINE_READONLY_UNSUPPORTED,
engine=row.engine,
)
try:
timeout = _clamp("timeout_ms", timeout_ms, MAX_TIMEOUT_MS)
limit = _clamp("max_rows", max_rows, MAX_ROWS_LIMIT)
declared = parse_output_schema(output_schema)
prepared = prepare_query(
engine=row.engine,
sql_template=sql_template,
param_schema=param_schema,
allowed_identifiers=allowed_identifiers,
params=params,
)
if row.kind != "database":
raise ValidationError(
"Unsupported datasource kind or engine",
details={"reason": "unsupported_datasource", "fields": ["kind", "engine"]},
)
target = datasource_service.build_probe_target(row)
except ValidationError as exc:
session.commit() # persists an auto-closed circuit and ends the read transaction
return failure(KIND_VALIDATION, _MESSAGES[KIND_VALIDATION], **exc.details)
# No transaction may stay open while the source database runs the statement.
session.commit()
connect_timeout = get_settings().datasource_probe_timeout_seconds
try:
fetched = drivers.fetch_rows(
target,
prepared.sql,
prepared.params,
timeout_ms=timeout,
limit=limit + 1,
connect_timeout=connect_timeout,
)
except UnsupportedDataSourceError:
return failure(
KIND_VALIDATION,
_MESSAGES[KIND_VALIDATION],
reason="unsupported_datasource",
fields=["kind", "engine"],
)
except drivers.ConnectFailure as exc:
return _connection_failure(session, ds_id, exc.category, row.engine)
except drivers.QueryFailure as exc:
if exc.category is not None:
return _connection_failure(session, ds_id, exc.category, row.engine)
kind = KIND_TIMEOUT if exc.kind == "timeout" else KIND_SQL_ERROR
logger.info("query run engine=%s datasource=%s status=failure kind=%s", row.engine, ds_id, kind)
return failure(kind, _MESSAGES[kind], **exc.details)
if len(fetched.rows) > limit:
logger.info("query run engine=%s datasource=%s status=failure kind=limit_exceeded", row.engine, ds_id)
return failure(
KIND_LIMIT_EXCEEDED, _MESSAGES[KIND_LIMIT_EXCEEDED], max_rows=limit
)
columns = list(fetched.columns)
if not fetched.rows:
logger.info("query run engine=%s datasource=%s status=empty", row.engine, ds_id)
return QueryRunResult(status=STATUS_EMPTY, message="query returned no rows", columns=columns)
problems = _type_problems(declared, columns, fetched.rows)
if problems:
logger.info("query run engine=%s datasource=%s status=illegal_type", row.engine, ds_id)
return QueryRunResult(
status=STATUS_ILLEGAL_TYPE,
message="query result violates the output schema",
columns=columns,
details={"fields": problems},
)
rows = [
{name: _json_value(value) for name, value in zip(columns, values)}
for values in fetched.rows
]
logger.info(
"query run engine=%s datasource=%s status=success rows=%d", row.engine, ds_id, len(rows)
)
return QueryRunResult(
status=STATUS_SUCCESS, message="query succeeded", columns=columns, rows=rows
)
def _connection_failure(
session: Session, ds_id: str, category: ProbeCategory, engine: str
) -> QueryRunResult:
"""Count the failure on the circuit (committed here) and return its classification."""
opened = datasource_service.record_connection_failure(session, ds_id, category)
session.commit()
kind = _CATEGORY_KIND.get(category, KIND_UNREACHABLE)
logger.info(
"query run engine=%s datasource=%s status=failure kind=%s circuit_opened=%s",
engine,
ds_id,
kind,
opened,
)
return failure(kind, _MESSAGES[kind], category=category.value, circuit_opened=opened)
@@ -0,0 +1,47 @@
"""Outcome type of one read-only query run.
Boundary: a plain value object; no I/O. status separates the four outcomes callers must
never confuse: success (rows), empty (zero rows), illegal_type (rows violate the output
contract) and failure (anything that stopped the run, classified by failure_kind).
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
STATUS_SUCCESS = "success"
STATUS_EMPTY = "empty"
STATUS_ILLEGAL_TYPE = "illegal_type"
STATUS_FAILURE = "failure"
# failure_kind values (status == failure only).
KIND_VALIDATION = "validation"
KIND_DISABLED = "disabled"
KIND_CIRCUIT_OPEN = "circuit_open"
KIND_TIMEOUT = "timeout"
KIND_UNREACHABLE = "unreachable"
KIND_AUTH_FAILED = "auth_failed"
KIND_REJECTED = "rejected"
KIND_LIMIT_EXCEEDED = "limit_exceeded"
KIND_SQL_ERROR = "sql_error"
# The engine has no server-enforced read-only session, so no user template is run on it.
KIND_ENGINE_READONLY_UNSUPPORTED = "engine_readonly_unsupported"
@dataclass(frozen=True)
class QueryRunResult:
"""One run's outcome. message is a fixed safe string (never driver text or data)."""
status: str
message: str
failure_kind: str | None = None
columns: list[str] = field(default_factory=list)
rows: list[dict[str, Any]] = field(default_factory=list)
details: dict[str, Any] = field(default_factory=dict)
def failure(kind: str, message: str, **details: Any) -> QueryRunResult:
return QueryRunResult(
status=STATUS_FAILURE, failure_kind=kind, message=message, details=dict(details)
)
@@ -0,0 +1,151 @@
"""Parameter and output schemas of a query template: parsing and value checks.
Boundary: pure validation of the JSON shapes stored on a query definition/version and of
single values against a declared type. No SQL, no database, no HTTP. Errors are the shared
ValidationError with a stable reason and field names, never echoing caller values.
"""
from __future__ import annotations
import math
import re
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
from typing import Any
from watchman.core.errors import ValidationError
VALUE_TYPES = ("string", "integer", "number", "boolean", "datetime")
# "nullish" is output-only: the column carries no type constraint (see check_output_value).
OUTPUT_TYPES = VALUE_TYPES + ("nullish",)
IDENTIFIER_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
_PARAM_KEYS = frozenset({"name", "type", "required", "default"})
_OUTPUT_KEYS = frozenset({"name", "type"})
_MAX_OUTPUT_NAME = 128
_MISSING = object()
@dataclass(frozen=True)
class ParamSpec:
name: str
type: str
required: bool
default: Any = _MISSING
@property
def has_default(self) -> bool:
return self.default is not _MISSING
def _invalid(reason: str, *fields: str) -> ValidationError:
return ValidationError(
"Invalid query definition", details={"reason": reason, "fields": list(fields)}
)
def coerce_param_value(spec_type: str, value: Any) -> Any:
"""Return `value` as a driver-bindable Python value of `spec_type` or raise ValueError."""
if spec_type == "string" and isinstance(value, str):
return value
if spec_type == "integer" and isinstance(value, int) and not isinstance(value, bool):
return value
if (
spec_type == "number"
and isinstance(value, (int, float, Decimal))
and not isinstance(value, bool)
and math.isfinite(float(value))
):
return value
if spec_type == "boolean" and isinstance(value, bool):
return value
if spec_type == "datetime":
if isinstance(value, datetime):
return value
if isinstance(value, str):
return datetime.fromisoformat(value) # ValueError on a bad string
raise ValueError("type mismatch")
def parse_param_schema(raw: Any) -> list[ParamSpec]:
"""Validate the param_schema list; unknown keys, duplicates and bad defaults are rejected."""
if not isinstance(raw, list):
raise _invalid("param_schema_invalid", "param_schema")
specs: list[ParamSpec] = []
seen: set[str] = set()
for item in raw:
if not isinstance(item, dict) or set(item) - _PARAM_KEYS:
raise _invalid("param_schema_invalid", "param_schema")
name, type_ = item.get("name"), item.get("type")
if not isinstance(name, str) or not IDENTIFIER_RE.match(name) or name in seen:
raise _invalid("param_schema_invalid", "param_schema")
if type_ not in VALUE_TYPES:
raise _invalid("param_schema_invalid", f"param_schema.{name}")
required = item.get("required", True)
if not isinstance(required, bool):
raise _invalid("param_schema_invalid", f"param_schema.{name}")
default = item.get("default", _MISSING)
if default is not _MISSING:
try:
default = coerce_param_value(type_, default)
except ValueError:
raise _invalid("param_default_invalid", f"param_schema.{name}") from None
seen.add(name)
specs.append(ParamSpec(name=name, type=type_, required=required, default=default))
return specs
def parse_output_schema(raw: Any) -> dict[str, str]:
"""Validate output_schema and return {column name: declared type}."""
if not isinstance(raw, list):
raise _invalid("output_schema_invalid", "output_schema")
result: dict[str, str] = {}
for item in raw:
if not isinstance(item, dict) or set(item) - _OUTPUT_KEYS:
raise _invalid("output_schema_invalid", "output_schema")
name, type_ = item.get("name"), item.get("type")
if (
not isinstance(name, str)
or not name
or len(name) > _MAX_OUTPUT_NAME
or name in result
or type_ not in OUTPUT_TYPES
):
raise _invalid("output_schema_invalid", "output_schema")
result[name] = type_
return result
def parse_allowed_identifiers(raw: Any) -> frozenset[str]:
if not isinstance(raw, list):
raise _invalid("allowed_identifiers_invalid", "allowed_identifiers")
if any(not isinstance(i, str) or not IDENTIFIER_RE.match(i) for i in raw):
raise _invalid("allowed_identifiers_invalid", "allowed_identifiers")
return frozenset(raw)
def check_output_value(declared_type: str, value: Any) -> bool:
"""True if a fetched value satisfies the declared output type.
SQL NULL satisfies every type (an absent value is not a type error; whether it is
acceptable is a rule-level question). "nullish" imposes no constraint at all.
"""
if value is None or declared_type == "nullish":
return True
if declared_type == "string":
return isinstance(value, str)
if declared_type == "integer":
return isinstance(value, int) and not isinstance(value, bool)
if declared_type == "number":
return (
isinstance(value, (int, float, Decimal))
and not isinstance(value, bool)
and math.isfinite(float(value))
)
if declared_type == "boolean":
return isinstance(value, bool)
if declared_type == "datetime":
return isinstance(value, datetime)
return False
@@ -0,0 +1,233 @@
"""SQL template preparation: named-parameter binding and whitelisted identifiers.
Boundary: pure text/value work, no connection. A template may contain `:name` parameters
(values, always bound by the driver, never spliced) and `{{ident}}` identifiers (only from
the declared allow-list, strictly [A-Za-z_][A-Za-z0-9_]*, substituted as quoted identifiers).
Placeholders inside string literals, quoted identifiers and comments are left alone, `::`
casts are not parameters, and a template must be one statement. This is structural
validation, not a read-only guarantee: that comes from the session settings and the
read-only account of the source.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Any
from watchman.core.errors import ValidationError
from watchman.queries.schema import (
IDENTIFIER_RE,
ParamSpec,
coerce_param_value,
parse_allowed_identifiers,
parse_param_schema,
)
_WORD = re.compile(r"[A-Za-z0-9_]")
_PARAM_NAME = re.compile(r":([A-Za-z_][A-Za-z0-9_]*)")
_DOLLAR_TAG = re.compile(r"\$([A-Za-z_][A-Za-z0-9_]*)?\$")
_QUOTE = {"postgresql": '"{}"', "mysql": "`{}`", "sqlserver": "[{}]"}
@dataclass(frozen=True)
class PreparedQuery:
"""Driver-ready statement. params is None when the statement has no parameters."""
sql: str
params: dict[str, Any] | None
def _bad(reason: str, *fields: str) -> ValidationError:
return ValidationError(
"Invalid query template", details={"reason": reason, "fields": list(fields)}
)
def _skip_quoted(sql: str, i: int, quote: str, *, backslash: bool, end: str | None = None) -> int:
"""Return the index just after the quoted run starting at sql[i]; doubled quotes escape."""
end = end or quote
j = i + 1
while j < len(sql):
ch = sql[j]
if backslash and ch == "\\":
j += 2
continue
if ch == end:
if sql[j + 1 : j + 2] == end:
j += 2
continue
return j + 1
j += 1
raise _bad("template_unterminated", "sql_template")
def _scan(sql: str, engine: str) -> list[tuple[str, str]]:
"""Split a template into ("text"|"param"|"ident", value) parts."""
parts: list[tuple[str, str]] = []
buf: list[str] = []
ended = False # a statement-terminating ';' was seen: only blanks/comments may follow
n = len(sql)
i = 0
def flush() -> None:
if buf:
parts.append(("text", "".join(buf)))
buf.clear()
def emit(raw: str, *, meaningful: bool) -> None:
if ended and meaningful:
raise _bad("multiple_statements", "sql_template")
buf.append(raw)
mysql = engine == "mysql"
while i < n:
ch = sql[i]
nxt = sql[i + 1 : i + 2]
if ch in ("'", '"'):
# Literal or quoted identifier. mysql and PG E'..' strings also use backslashes.
prev = sql[i - 1] if i else ""
e_string = (
engine == "postgresql"
and ch == "'"
and prev in ("e", "E")
and not (i >= 2 and _WORD.match(sql[i - 2]))
)
j = _skip_quoted(sql, i, ch, backslash=mysql or e_string)
emit(sql[i:j], meaningful=True)
i = j
elif ch == "`" and mysql:
j = _skip_quoted(sql, i, "`", backslash=False)
emit(sql[i:j], meaningful=True)
i = j
elif ch == "[" and engine == "sqlserver":
j = _skip_quoted(sql, i, "[", backslash=False, end="]")
emit(sql[i:j], meaningful=True)
i = j
elif (ch == "-" and nxt == "-") or (ch == "#" and mysql):
j = sql.find("\n", i)
j = n if j == -1 else j
emit(sql[i:j], meaningful=False)
i = j
elif ch == "/" and nxt == "*":
j = sql.find("*/", i + 2)
if j == -1:
raise _bad("template_unterminated", "sql_template")
emit(sql[i : j + 2], meaningful=False)
i = j + 2
elif ch == "$" and engine == "postgresql" and not (i and _WORD.match(sql[i - 1])):
tag = _DOLLAR_TAG.match(sql, i)
if tag is None:
emit(ch, meaningful=True)
i += 1
continue
j = sql.find(tag.group(0), tag.end())
if j == -1:
raise _bad("template_unterminated", "sql_template")
emit(sql[i : j + len(tag.group(0))], meaningful=True)
i = j + len(tag.group(0))
elif ch == ":" and nxt == ":":
emit("::", meaningful=True)
i += 2
elif ch == ":":
match = _PARAM_NAME.match(sql, i)
if match and not (i and _WORD.match(sql[i - 1])):
if ended:
raise _bad("multiple_statements", "sql_template")
flush()
parts.append(("param", match.group(1)))
i = match.end()
else:
emit(ch, meaningful=True)
i += 1
elif ch == "{" and nxt == "{":
j = sql.find("}}", i + 2)
if j == -1:
raise _bad("identifier_unterminated", "sql_template")
if ended:
raise _bad("multiple_statements", "sql_template")
flush()
parts.append(("ident", sql[i + 2 : j].strip()))
i = j + 2
elif ch == ";":
if ended:
raise _bad("multiple_statements", "sql_template")
ended = True
i += 1 # the terminator itself is dropped
else:
emit(ch, meaningful=not ch.isspace())
i += 1
flush()
return parts
def prepare_query(
*,
engine: str,
sql_template: str,
param_schema: Any,
allowed_identifiers: Any,
params: Any,
) -> PreparedQuery:
"""Validate everything, then return SQL with `%(name)s` markers and the bound values.
Raises ValidationError before any connection when: a parameter is unknown, missing or
mistyped, a placeholder is undeclared, an identifier is malformed or not allowed, or
the template is not a single statement. Caller values are never echoed in errors.
"""
if engine not in _QUOTE:
raise _bad("unsupported_engine", "engine")
if not isinstance(sql_template, str) or not sql_template.strip():
raise _bad("template_empty", "sql_template")
specs = {spec.name: spec for spec in parse_param_schema(param_schema)}
allowed = parse_allowed_identifiers(allowed_identifiers)
supplied = {} if params is None else params
if not isinstance(supplied, dict):
raise _bad("params_invalid", "params")
unknown = sorted(str(k)[:64] for k in supplied if k not in specs)[:10]
if unknown:
raise _bad("unknown_param", *unknown)
bound: dict[str, Any] = {}
for spec in specs.values():
bound[spec.name] = _resolve(spec, supplied)
parts = _scan(sql_template, engine)
used: set[str] = set()
for kind, value in parts:
if kind == "param":
if value not in specs:
raise _bad("undeclared_param", value)
used.add(value)
elif kind == "ident":
if not IDENTIFIER_RE.match(value):
raise _bad("identifier_invalid", "sql_template")
if value not in allowed:
raise _bad("identifier_not_allowed", value)
if not used:
# Nothing to bind: a '%' in the text must stay literal, so pass no parameters.
out = "".join(_render(kind, value, engine, escape=False) for kind, value in parts)
return PreparedQuery(sql=out.strip(), params=None)
out = "".join(_render(kind, value, engine, escape=True) for kind, value in parts)
return PreparedQuery(sql=out.strip(), params={name: bound[name] for name in used})
def _resolve(spec: ParamSpec, supplied: dict[str, Any]) -> Any:
if spec.name in supplied:
try:
return coerce_param_value(spec.type, supplied[spec.name])
except ValueError:
raise _bad("param_type_mismatch", spec.name) from None
if spec.required:
raise _bad("missing_param", spec.name)
return spec.default if spec.has_default else None
def _render(kind: str, value: str, engine: str, *, escape: bool) -> str:
if kind == "param":
return f"%({value})s"
if kind == "ident":
return _QUOTE[engine].format(value)
return value.replace("%", "%%") if escape else value
@@ -15,7 +15,7 @@ import uuid
from datetime import datetime, timedelta, timezone
from typing import Any
from sqlalchemy import select
from sqlalchemy import asc, desc, func, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
@@ -29,7 +29,8 @@ from watchman.datasources import (
UnsupportedDataSourceError,
probe_datasource,
)
from watchman.models.datasource import DataSource, validate_kind_engine
from watchman.models.datasource import ALLOWED_ENGINES, DataSource, validate_kind_engine
from watchman.models.query import QueryDefinition
from watchman.services.platform_records import create_audit_event
# Only these probe categories are worth retrying; the others need a config change.
@@ -235,12 +236,30 @@ def _audit(session: Session, action: str, row: DataSource, **extra: Any) -> None
)
_DS_SORT = {
"name": DataSource.name,
"engine": DataSource.engine,
"host": DataSource.host,
"port": DataSource.port,
"database_name": DataSource.database_name,
"username": DataSource.username,
"enabled": DataSource.enabled,
"last_test_at": DataSource.last_test_at,
"created_at": DataSource.created_at,
"updated_at": DataSource.updated_at,
}
_DS_SORT_DEFAULT = "created_at"
_LIST_PAGE_SIZE_MAX = 100
def list_datasources(session: Session, *, usable_only: bool = False) -> list[DataSource]:
"""Return datasources of the server tenant, oldest first.
Every returned row first has an elapsed circuit cooldown closed (time only, no probe),
so the exposed circuit state is never stale; the caller commits to persist that.
usable_only then keeps rows that are enabled and whose circuit is closed.
Healthcheck and option dropdowns use this complete list; the console table uses
search_datasources so filters, ORDER BY and LIMIT run in SQL.
"""
rows = list(
session.scalars(
@@ -257,6 +276,62 @@ def list_datasources(session: Session, *, usable_only: bool = False) -> list[Dat
return [row for row in rows if row.enabled and row.circuit_state != CIRCUIT_OPEN]
def search_datasources(
session: Session,
*,
name: str | None = None,
engine: str | None = None,
enabled: bool | None = None,
sort_by: str = _DS_SORT_DEFAULT,
sort_order: str = "asc",
page: int = 1,
page_size: int = 20,
) -> dict[str, Any]:
"""Filter, ORDER BY and page datasources in SQL for the console list.
Cooldown close runs on the returned page only so circuit state in the page is fresh;
the caller commits. usable_only option lists still go through list_datasources.
"""
if sort_by not in _DS_SORT:
raise ValidationError("Invalid sort_by", details={"field": "sort_by", "allowed": sorted(_DS_SORT)})
if sort_order not in ("asc", "desc"):
raise ValidationError("Invalid sort_order", details={"field": "sort_order", "allowed": ["asc", "desc"]})
if page < 1:
raise ValidationError("Invalid page", details={"field": "page"})
if page_size < 1 or page_size > _LIST_PAGE_SIZE_MAX:
raise ValidationError(
"Invalid page_size",
details={"field": "page_size", "min": 1, "max": _LIST_PAGE_SIZE_MAX},
)
if engine is not None and engine not in ALLOWED_ENGINES:
raise ValidationError("Invalid engine", details={"field": "engine"})
filters = [DataSource.tenant_id == _tenant_id()]
needle = (name or "").strip()
if needle:
filters.append(DataSource.name.ilike(f"%{needle}%"))
if engine:
filters.append(DataSource.engine == engine)
if enabled is not None:
filters.append(DataSource.enabled.is_(enabled))
total = int(session.scalar(select(func.count()).select_from(DataSource).where(*filters)) or 0)
order_col = _DS_SORT[sort_by]
order_expr = asc(order_col) if sort_order == "asc" else desc(order_col)
stmt = (
select(DataSource)
.where(*filters)
.order_by(order_expr, asc(DataSource.id))
.offset((page - 1) * page_size)
.limit(page_size)
)
rows = list(session.scalars(stmt))
now = _now()
for row in rows:
_close_if_cooled_down(row, now)
return {"items": rows, "total": total, "page": page, "page_size": page_size}
def get_datasource(session: Session, datasource_id: str) -> DataSource:
"""Return one datasource or raise 404.
@@ -456,9 +531,20 @@ def record_probe_outcome(
def list_references(session: Session, datasource_id: str) -> dict[str, Any]:
"""Return the references to a datasource. No module references datasources yet."""
"""Return what references a datasource: the query definitions bound to it (read-only hint)."""
row = _get_row(session, datasource_id)
return {"id": str(row.id), "items": []}
queries = session.scalars(
select(QueryDefinition)
.where(
QueryDefinition.tenant_id == _tenant_id(),
QueryDefinition.datasource_id == row.id,
)
.order_by(QueryDefinition.name)
)
items = [
{"type": "query", "id": str(q.id), "name": q.name, "enabled": q.enabled} for q in queries
]
return {"id": str(row.id), "items": items}
def _probe(target: ProbeTarget) -> ProbeResult:
@@ -484,6 +570,42 @@ def _decrypt_stored(row: DataSource) -> str:
raise DatasourceSecretUnavailableError() from None
def build_probe_target(row: DataSource) -> ProbeTarget:
"""Build a connection target from the stored row; the password lives only in memory.
Raises DatasourceSecretUnavailableError when the stored secret cannot be decrypted.
"""
return ProbeTarget(
engine=row.engine,
kind=row.kind,
host=row.host,
port=row.port,
database=row.database_name,
username=row.username,
password=_decrypt_stored(row),
)
def record_connection_failure(
session: Session, datasource_id: str, category: ProbeCategory
) -> bool:
"""Count one failed connection of a real query run against the circuit.
Same accounting as a saved-connection test (window, threshold, circuit_open audit) but
last_test_* is left alone because no test was run. A source deleted meanwhile is
ignored. The caller commits. Returns True if the circuit opened.
"""
if category is ProbeCategory.SUCCESS:
return False
try:
row = _get_row(session, datasource_id, lock=True)
except NotFoundError:
session.rollback()
return False
result = ProbeResult(category=category, message=f"query run: {category.value}")
return record_probe_outcome(session, row, result, update_last_test=False)
def run_connection_test(session: Session, datasource_id: str) -> tuple[DataSource, ProbeResult]:
"""Probe the saved connection, record last_test and circuit accounting; the caller commits.
@@ -0,0 +1,719 @@
"""Query definition service: metadata CRUD, save-as-version, activate, versions and preview.
Why: the console saves immutable numbered versions (D26: no draft/publish two-step), activates
one as current, and trial-runs the current or a chosen version.
Boundary: tenant comes only from server settings; a QueryVersion is only ever inserted, never
updated or deleted. draft_* columns mirror the current version for transitional internals and
are not an editable draft API. Preview delegates to watchman.queries.run_query; it never
persists rows or creates alarms. Callers own the final commit; preview_* commits inside
run_query, then audit once.
Depends on the query models, the datasource service, the S2 executor and create_audit_event.
"""
from __future__ import annotations
import re
import uuid
from datetime import datetime, timezone
from typing import Any
from sqlalchemy import asc, desc, func, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from watchman.core.config import get_settings
from watchman.core.errors import ConflictError, NotFoundError, ValidationError
from watchman.models.datasource import DataSource
from watchman.models.query import (
DEFAULT_MAX_ROWS,
DEFAULT_TIMEOUT_MS,
MAX_ROWS_LIMIT,
MAX_TIMEOUT_MS,
QueryDefinition,
QueryVersion,
)
from watchman.queries import QueryRunResult, run_query
from watchman.queries.schema import (
parse_allowed_identifiers,
parse_output_schema,
parse_param_schema,
)
from watchman.services import datasources as datasource_service
from watchman.services.platform_records import create_audit_event
# Draft fields a create or PATCH may set; API name -> definition column.
_DRAFT_COLUMNS = {
"sql_template": "draft_sql_template",
"param_schema": "draft_param_schema",
"output_schema": "draft_output_schema",
"allowed_identifiers": "draft_allowed_identifiers",
"timeout_ms": "draft_timeout_ms",
"max_rows": "draft_max_rows",
}
# Plain definition fields (not draft content) a PATCH may set; only description may be null.
_PLAIN_FIELDS = ("name", "description", "datasource_id")
MAX_PUBLISHED_BY_LENGTH = 128
# Preview rows are samples: values of columns whose name looks sensitive are masked. The
# output contract carries no sensitivity flag, so this is a simple name-based policy.
SENSITIVE_COLUMN_RE = re.compile(
r"pass(word|wd)?|pwd|secret|token|credential|api[_-]?key|private[_-]?key|"
r"id[_-]?card|phone|mobile|email",
re.IGNORECASE,
)
MASK = "***"
def _now() -> datetime:
return datetime.now(timezone.utc)
def _tenant_id() -> str:
# GUARD: tenant is never taken from a request.
return get_settings().tenant_id
def _isoformat(value: datetime | None) -> str | None:
# Always UTC: a just-written value (UTC) and a re-read one (session zone) must match.
return value.astimezone(timezone.utc).isoformat() if value is not None else None
def _parse_id(query_id: str) -> uuid.UUID:
try:
return uuid.UUID(query_id)
except ValueError:
# An id that cannot exist is the same as an unknown id.
raise NotFoundError("Query not found") from None
def content_from_draft_columns(row: QueryDefinition) -> dict[str, Any]:
"""Mirrored content from draft_* columns (same keys as a version body)."""
return {
"sql_template": row.draft_sql_template,
"param_schema": row.draft_param_schema,
"output_schema": row.draft_output_schema,
"allowed_identifiers": row.draft_allowed_identifiers,
"timeout_ms": row.draft_timeout_ms,
"max_rows": row.draft_max_rows,
}
def _mirror_draft(row: QueryDefinition, content: dict[str, Any]) -> None:
"""Keep draft_* in sync with the active version content (D26 transitional mirror)."""
for key, column in _DRAFT_COLUMNS.items():
setattr(row, column, content[key])
def summary_public(row: QueryDefinition) -> dict[str, Any]:
"""List item: identity, state and version pointers; no SQL content."""
return {
"id": str(row.id),
"name": row.name,
"description": row.description,
"datasource_id": str(row.datasource_id),
"enabled": row.enabled,
"current_version_no": row.current_version_no,
"latest_version_no": row.latest_published_version_no,
# Legacy alias kept for older clients during the transition.
"latest_published_version_no": row.latest_published_version_no,
"created_at": _isoformat(row.created_at),
"updated_at": _isoformat(row.updated_at),
}
def to_public(row: QueryDefinition) -> dict[str, Any]:
"""Detail: summary plus the current version content snapshot (not a draft)."""
return {**summary_public(row), "current": content_from_draft_columns(row)}
def version_summary(row: QueryVersion) -> dict[str, Any]:
"""Version list item: number and provenance only."""
return {
"id": str(row.id),
"definition_id": str(row.definition_id),
"version_no": row.version_no,
"published_at": _isoformat(row.published_at),
"published_by": row.published_by,
}
def version_public(row: QueryVersion) -> dict[str, Any]:
"""Full frozen version content."""
return {
**version_summary(row),
"sql_template": row.sql_template,
"param_schema": row.param_schema,
"output_schema": row.output_schema,
"allowed_identifiers": row.allowed_identifiers,
"timeout_ms": row.timeout_ms,
"max_rows": row.max_rows,
}
def _get_row(session: Session, query_id: str, *, lock: bool = False) -> QueryDefinition:
"""Load one definition of the server tenant or raise 404 (also for other tenants)."""
statement = select(QueryDefinition).where(
QueryDefinition.id == _parse_id(query_id),
QueryDefinition.tenant_id == _tenant_id(),
)
if lock:
statement = statement.execution_options(populate_existing=True).with_for_update()
row = session.scalar(statement)
if row is None:
raise NotFoundError("Query not found")
return row
def _get_version(session: Session, definition: QueryDefinition, version_no: int) -> QueryVersion:
row = session.scalar(
select(QueryVersion).where(
QueryVersion.tenant_id == _tenant_id(),
QueryVersion.definition_id == definition.id,
QueryVersion.version_no == version_no,
)
)
if row is None:
raise NotFoundError("Query version not found")
return row
def _check_datasource(session: Session, datasource_id: str) -> uuid.UUID:
"""The datasource must exist for this tenant and be a database source."""
try:
source = datasource_service.get_datasource(session, datasource_id)
except NotFoundError:
raise ValidationError(
"Datasource not found",
details={"reason": "datasource_not_found", "fields": ["datasource_id"]},
) from None
if source.kind != "database":
raise ValidationError(
"Queries can only use a database datasource",
details={"reason": "datasource_not_database", "fields": ["datasource_id"]},
)
return source.id
def _validate_draft_content(values: dict[str, Any]) -> None:
"""Reject malformed draft content; reuses the executor's schema parsers (no SQL parsing)."""
if "sql_template" in values:
sql = values["sql_template"]
if not isinstance(sql, str) or not sql.strip():
raise ValidationError(
"Invalid query definition",
details={"reason": "template_empty", "fields": ["sql_template"]},
)
if "param_schema" in values:
parse_param_schema(values["param_schema"])
if "output_schema" in values:
parse_output_schema(values["output_schema"])
if "allowed_identifiers" in values:
parse_allowed_identifiers(values["allowed_identifiers"])
def _cap_limit(name: str, value: Any, maximum: int) -> int:
"""A limit must be an int >= 1; one above the server cap is capped, not rejected."""
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
raise ValidationError(
"Invalid query limits", details={"reason": "limit_invalid", "fields": [name]}
)
return min(value, maximum)
def _normalize_limits(values: dict[str, Any]) -> None:
if "timeout_ms" in values:
values["timeout_ms"] = _cap_limit("timeout_ms", values["timeout_ms"], MAX_TIMEOUT_MS)
if "max_rows" in values:
values["max_rows"] = _cap_limit("max_rows", values["max_rows"], MAX_ROWS_LIMIT)
def _ensure_name_free(session: Session, name: str, *, exclude_id: uuid.UUID | None = None) -> None:
statement = select(QueryDefinition.id).where(
QueryDefinition.tenant_id == _tenant_id(),
QueryDefinition.name == name,
)
if exclude_id is not None:
statement = statement.where(QueryDefinition.id != exclude_id)
if session.scalar(statement) is not None:
raise ConflictError("Query name already exists", details={"reason": "duplicate_name"})
def _flush_unique(session: Session) -> None:
"""Flush, turning a racing duplicate-name insert or update into the same 409."""
try:
with session.begin_nested():
session.flush()
except IntegrityError:
raise ConflictError(
"Query name already exists", details={"reason": "duplicate_name"}
) from None
def _audit(session: Session, action: str, payload: dict[str, Any]) -> None:
"""Write an audit event with a server-generated key. Payloads never hold SQL or rows."""
create_audit_event(
session,
action=action,
payload=payload,
idempotency_key=f"{action}:{uuid.uuid4().hex}",
)
# Console list sort keys → SQL columns (datasource_name needs a join).
_QUERY_SORT = {
"name": QueryDefinition.name,
"enabled": QueryDefinition.enabled,
"latest_published_version_no": QueryDefinition.latest_published_version_no,
"current_version_no": QueryDefinition.current_version_no,
"updated_at": QueryDefinition.updated_at,
"created_at": QueryDefinition.created_at,
"datasource_name": DataSource.name,
}
_QUERY_SORT_DEFAULT = "updated_at"
_LIST_PAGE_SIZE_MAX = 100
def list_queries(session: Session, *, enabled: bool | None = None) -> list[QueryDefinition]:
"""Return definitions of the server tenant, oldest first; enabled filters when given.
Internal callers (seed, references) use this complete list. The console list uses
search_queries so filters, ORDER BY and LIMIT run in SQL.
"""
statement = select(QueryDefinition).where(QueryDefinition.tenant_id == _tenant_id())
if enabled is not None:
statement = statement.where(QueryDefinition.enabled.is_(enabled))
return list(
session.scalars(statement.order_by(QueryDefinition.created_at, QueryDefinition.name))
)
def search_queries(
session: Session,
*,
enabled: bool | None = None,
name: str | None = None,
datasource_id: str | None = None,
sort_by: str = _QUERY_SORT_DEFAULT,
sort_order: str = "desc",
page: int = 1,
page_size: int = 20,
) -> dict[str, Any]:
"""Filter, ORDER BY and page query definitions in SQL for the console list."""
if sort_by not in _QUERY_SORT:
raise ValidationError("Invalid sort_by", details={"field": "sort_by", "allowed": sorted(_QUERY_SORT)})
if sort_order not in ("asc", "desc"):
raise ValidationError("Invalid sort_order", details={"field": "sort_order", "allowed": ["asc", "desc"]})
if page < 1:
raise ValidationError("Invalid page", details={"field": "page"})
if page_size < 1 or page_size > _LIST_PAGE_SIZE_MAX:
raise ValidationError(
"Invalid page_size",
details={"field": "page_size", "min": 1, "max": _LIST_PAGE_SIZE_MAX},
)
tenant = _tenant_id()
filters = [QueryDefinition.tenant_id == tenant]
if enabled is not None:
filters.append(QueryDefinition.enabled.is_(enabled))
needle = (name or "").strip()
if needle:
filters.append(QueryDefinition.name.ilike(f"%{needle}%"))
if datasource_id:
try:
ds_uuid = uuid.UUID(datasource_id)
except ValueError as exc:
raise ValidationError(
"Invalid datasource_id", details={"field": "datasource_id"}
) from exc
filters.append(QueryDefinition.datasource_id == ds_uuid)
# Join when sorting by datasource display name; otherwise stay on the definition table.
needs_join = sort_by == "datasource_name"
count_stmt = select(func.count()).select_from(QueryDefinition).where(*filters)
total = int(session.scalar(count_stmt) or 0)
order_col = _QUERY_SORT[sort_by]
order_expr = asc(order_col) if sort_order == "asc" else desc(order_col)
# Stable tie-break so equal sort keys do not reshuffle across pages.
tie_break = asc(QueryDefinition.id)
stmt = select(QueryDefinition).where(*filters)
if needs_join:
stmt = stmt.join(DataSource, DataSource.id == QueryDefinition.datasource_id)
stmt = (
stmt.order_by(order_expr, tie_break)
.offset((page - 1) * page_size)
.limit(page_size)
)
rows = list(session.scalars(stmt))
return {"items": rows, "total": total, "page": page, "page_size": page_size}
def get_query(session: Session, query_id: str) -> QueryDefinition:
"""Return one definition or raise 404."""
return _get_row(session, query_id)
def _insert_version(
session: Session,
row: QueryDefinition,
content: dict[str, Any],
*,
version_no: int,
published_by: str | None,
) -> QueryVersion:
version = QueryVersion(
tenant_id=row.tenant_id,
definition_id=row.id,
version_no=version_no,
sql_template=content["sql_template"],
param_schema=content["param_schema"],
output_schema=content["output_schema"],
allowed_identifiers=content["allowed_identifiers"],
timeout_ms=content["timeout_ms"],
max_rows=content["max_rows"],
published_at=_now(),
published_by=published_by[:MAX_PUBLISHED_BY_LENGTH] if published_by else None,
)
session.add(version)
try:
with session.begin_nested():
session.flush()
except IntegrityError:
raise ConflictError(
"Query version already exists", details={"reason": "version_conflict"}
) from None
return version
def create_query(
session: Session,
*,
name: str,
description: str | None,
datasource_id: str,
sql_template: str,
param_schema: list[Any] | None = None,
output_schema: list[Any] | None = None,
allowed_identifiers: list[Any] | None = None,
timeout_ms: int = DEFAULT_TIMEOUT_MS,
max_rows: int = DEFAULT_MAX_ROWS,
published_by: str | None = None,
) -> QueryDefinition:
"""Create an enabled definition with immutable v1 as current (D26)."""
content: dict[str, Any] = {
"sql_template": sql_template,
"param_schema": [] if param_schema is None else param_schema,
"output_schema": [] if output_schema is None else output_schema,
"allowed_identifiers": [] if allowed_identifiers is None else allowed_identifiers,
"timeout_ms": timeout_ms,
"max_rows": max_rows,
}
_validate_draft_content(content)
_normalize_limits(content)
ds_id = _check_datasource(session, datasource_id)
_ensure_name_free(session, name)
now = _now()
row = QueryDefinition(
tenant_id=_tenant_id(),
name=name,
description=description,
datasource_id=ds_id,
enabled=True,
latest_published_version_no=1,
current_version_no=1,
created_at=now,
updated_at=now,
**{_DRAFT_COLUMNS[key]: value for key, value in content.items()},
)
session.add(row)
_flush_unique(session)
_insert_version(session, row, content, version_no=1, published_by=published_by)
_audit(
session,
"query.create",
{
"id": str(row.id),
"name": row.name,
"datasource_id": str(row.datasource_id),
"version_no": 1,
},
)
return row
def update_query(session: Session, query_id: str, changes: dict[str, Any]) -> QueryDefinition:
"""Update definition metadata only. Content changes must use save_as_version (D26)."""
row = _get_row(session, query_id)
content_keys = [key for key in _DRAFT_COLUMNS if key in changes]
if content_keys:
raise ValidationError(
"Query content cannot be patched; save a new version",
details={"reason": "use_save_version", "fields": content_keys},
)
nulled = [f for f in _PLAIN_FIELDS if f != "description" and f in changes and changes[f] is None]
if nulled:
raise ValidationError("Fields cannot be null", details={"fields": nulled})
if "datasource_id" in changes:
row.datasource_id = _check_datasource(session, changes["datasource_id"])
if "name" in changes and changes["name"] != row.name:
_ensure_name_free(session, changes["name"], exclude_id=row.id)
row.name = changes["name"]
if "description" in changes:
row.description = changes["description"]
row.updated_at = _now()
_flush_unique(session)
changed = [f for f in _PLAIN_FIELDS if f in changes]
_audit(
session,
"query.update",
{"id": str(row.id), "name": row.name, "fields": changed},
)
return row
def save_as_version(
session: Session,
query_id: str,
content: dict[str, Any],
*,
published_by: str | None = None,
) -> QueryVersion:
"""Insert the next immutable version, activate it, and mirror draft_* (D26)."""
row = _get_row(session, query_id, lock=True)
body = {
"sql_template": content["sql_template"],
"param_schema": content.get("param_schema") or [],
"output_schema": content.get("output_schema") or [],
"allowed_identifiers": content.get("allowed_identifiers") or [],
"timeout_ms": content.get("timeout_ms", DEFAULT_TIMEOUT_MS),
"max_rows": content.get("max_rows", DEFAULT_MAX_ROWS),
}
_validate_draft_content(body)
_normalize_limits(body)
version_no = (row.latest_published_version_no or 0) + 1
version = _insert_version(
session, row, body, version_no=version_no, published_by=published_by
)
row.latest_published_version_no = version_no
row.current_version_no = version_no
_mirror_draft(row, body)
row.updated_at = _now()
session.flush()
_audit(
session,
"query.save_version",
{"id": str(row.id), "name": row.name, "version_no": version_no},
)
return version
def activate_version(
session: Session, query_id: str, version_no: int
) -> QueryDefinition:
"""Set current_version_no to an existing version and mirror its content into draft_*."""
if version_no < 1:
raise ValidationError("Invalid version_no", details={"field": "version_no"})
row = _get_row(session, query_id, lock=True)
version = _get_version(session, row, version_no)
content = {
"sql_template": version.sql_template,
"param_schema": version.param_schema,
"output_schema": version.output_schema,
"allowed_identifiers": version.allowed_identifiers,
"timeout_ms": version.timeout_ms,
"max_rows": version.max_rows,
}
row.current_version_no = version.version_no
_mirror_draft(row, content)
row.updated_at = _now()
session.flush()
_audit(
session,
"query.activate_version",
{"id": str(row.id), "name": row.name, "version_no": version.version_no},
)
return row
def _set_enabled(session: Session, query_id: str, enabled: bool) -> QueryDefinition:
row = _get_row(session, query_id)
row.enabled = enabled
row.updated_at = _now()
session.flush()
_audit(
session,
"query.enable" if enabled else "query.disable",
{"id": str(row.id), "name": row.name},
)
return row
def disable_query(session: Session, query_id: str) -> QueryDefinition:
"""Mark a definition disabled. It stays readable and can be enabled again."""
return _set_enabled(session, query_id, False)
def enable_query(session: Session, query_id: str) -> QueryDefinition:
"""Mark a definition enabled again."""
return _set_enabled(session, query_id, True)
def list_versions(session: Session, query_id: str) -> list[QueryVersion]:
"""Return the versions of one definition, newest first."""
row = _get_row(session, query_id)
return list(
session.scalars(
select(QueryVersion)
.where(
QueryVersion.tenant_id == _tenant_id(),
QueryVersion.definition_id == row.id,
)
.order_by(QueryVersion.version_no.desc())
)
)
def get_version(session: Session, query_id: str, version_no: int) -> QueryVersion:
"""Return one frozen version or raise 404."""
return _get_version(session, _get_row(session, query_id), version_no)
def list_references(session: Session, query_id: str) -> dict[str, Any]:
"""Return what references this query. No scenario module exists yet, so items is empty."""
row = _get_row(session, query_id)
return {"id": str(row.id), "items": []}
def _mask_rows(columns: list[str], rows: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], list[str]]:
"""Replace non-null values of sensitive-looking columns with a fixed mask."""
masked = [name for name in columns if SENSITIVE_COLUMN_RE.search(name)]
if not masked:
return rows, []
out = [
{k: (MASK if k in masked and v is not None else v) for k, v in row.items()}
for row in rows
]
return out, masked
def preview_public(
result: QueryRunResult,
*,
definition_id: str,
version_no: int | None,
source: str = "version",
) -> dict[str, Any]:
"""Map one run outcome to the API shape. Distinct fields per status, no secrets.
success/empty carry columns, rows and row_count; illegal_type carries details.fields
(names and types only); failure carries failure_kind and its safe details.
"""
data: dict[str, Any] = {
"id": definition_id,
"version_no": version_no,
"source": source,
"status": result.status,
"message": result.message,
}
if result.status in ("success", "empty"):
rows, masked = _mask_rows(result.columns, result.rows)
data.update(columns=result.columns, rows=rows, row_count=len(rows), masked_columns=masked)
elif result.status == "illegal_type":
data.update(columns=result.columns, details=result.details)
else:
data.update(failure_kind=result.failure_kind, details=result.details)
return data
def _require_enabled(row: QueryDefinition) -> None:
if not row.enabled:
raise ConflictError("Query is disabled", details={"reason": "disabled"})
def _run_and_audit(
session: Session,
*,
definition_id: str,
version_no: int | None,
datasource_id: str,
content: dict[str, Any],
params: dict[str, Any],
source: str = "version",
) -> dict[str, Any]:
# `content` was copied out of the ORM rows: run_query commits the session.
result = run_query(
session,
datasource_id=datasource_id,
sql_template=content["sql_template"],
param_schema=content["param_schema"],
output_schema=content["output_schema"],
allowed_identifiers=content["allowed_identifiers"],
params=params,
timeout_ms=content["timeout_ms"],
max_rows=content["max_rows"],
)
# GUARD: only definition id, version_no (if any) and status; no name, SQL, rows, columns,
# parameter values or messages.
payload: dict[str, Any] = {"id": definition_id, "status": result.status}
if version_no is not None:
payload["version_no"] = version_no
_audit(session, "query.preview", payload)
return preview_public(
result, definition_id=definition_id, version_no=version_no, source=source
)
def preview_current(session: Session, query_id: str, params: dict[str, Any]) -> dict[str, Any]:
"""Trial-run the current active version. Disabled definitions are refused (409)."""
row = _get_row(session, query_id)
_require_enabled(row)
if row.current_version_no is None:
raise ConflictError("Query has no current version", details={"reason": "no_current_version"})
version = _get_version(session, row, row.current_version_no)
return _run_and_audit(
session,
definition_id=str(row.id),
version_no=version.version_no,
datasource_id=str(row.datasource_id),
content={
"sql_template": version.sql_template,
"param_schema": version.param_schema,
"output_schema": version.output_schema,
"allowed_identifiers": version.allowed_identifiers,
"timeout_ms": version.timeout_ms,
"max_rows": version.max_rows,
},
params=params,
source="current",
)
# Temporary alias for call sites still named preview_draft during the transition.
preview_draft = preview_current
def preview_version(
session: Session, query_id: str, version_no: int, params: dict[str, Any]
) -> dict[str, Any]:
"""Trial-run a frozen version against the definition's datasource (409 if disabled)."""
row = _get_row(session, query_id)
_require_enabled(row)
version = _get_version(session, row, version_no)
return _run_and_audit(
session,
definition_id=str(row.id),
version_no=version.version_no,
datasource_id=str(row.datasource_id),
content={
"sql_template": version.sql_template,
"param_schema": version.param_schema,
"output_schema": version.output_schema,
"allowed_identifiers": version.allowed_identifiers,
"timeout_ms": version.timeout_ms,
"max_rows": version.max_rows,
},
params=params,
source="version",
)
@@ -0,0 +1,36 @@
"""Immutability guard for published query versions.
Boundary: refuses content changes to an existing QueryVersion; snapshotting a draft into a
new version belongs to a later slice. Identity and audit columns (published_at/published_by)
are frozen too, because a version is a historical record. No database access, no HTTP concerns.
Depends on the QueryVersion model and the shared semantic errors.
"""
from __future__ import annotations
from collections.abc import Mapping
from typing import Any
from watchman.core.errors import ValidationError
from watchman.models.query import VERSION_CONTENT_COLUMNS, QueryVersion
# Identity/audit columns are frozen as well; changing them would rewrite history.
_FROZEN_COLUMNS = VERSION_CONTENT_COLUMNS | frozenset(
{"tenant_id", "definition_id", "version_no", "published_at", "published_by"}
)
def forbid_version_content_mutation(changes: Mapping[str, Any]) -> None:
"""Raise ValidationError if `changes` touches any frozen column of a published version."""
touched = sorted(set(changes) & _FROZEN_COLUMNS)
if touched:
raise ValidationError(
"published query versions are immutable; publish a new version instead",
details={"reason": "version_immutable", "fields": touched},
)
def assert_version_immutable(version: QueryVersion, changes: Mapping[str, Any]) -> QueryVersion:
"""Return `version` untouched, or raise if `changes` would rewrite it (never mutates it)."""
forbid_version_content_mutation(changes)
return version
@@ -0,0 +1,52 @@
"""Superuser-only purge of query rows created by tests.
query_versions is append-only for the application and migrator roles (migration 0007), so a
test cannot delete the versions it published through the app session. Cleanup therefore
connects with the local bootstrap superuser and opts out of the append-only trigger with
`SET LOCAL session_replication_role = replica`. Only synthetic rows carrying a test name
prefix or belonging to a given datasource are removed. Never used by production code.
"""
from __future__ import annotations
import uuid
from sqlalchemy import create_engine, text
from sqlalchemy.engine import make_url
from watchman.core.config import get_settings, merge_layered_env
def _superuser_engine(): # type: ignore[no-untyped-def]
env = merge_layered_env()
bootstrap = env.get("WATCHMAN_BOOTSTRAP_DATABASE_URL")
if not bootstrap:
raise RuntimeError(
"WATCHMAN_BOOTSTRAP_DATABASE_URL is required to clean up append-only query_versions rows"
)
database = make_url(get_settings().database_url).database
return create_engine(make_url(bootstrap).set(database=database), pool_pre_ping=True)
def purge_query_rows(
*, name_like: str | None = None, datasource_id: uuid.UUID | str | None = None
) -> None:
"""Delete query versions and definitions matched by name prefix or datasource."""
if (name_like is None) == (datasource_id is None):
raise ValueError("pass exactly one of name_like or datasource_id")
where = "name LIKE :v" if name_like is not None else "datasource_id = :v"
value = name_like if name_like is not None else str(datasource_id)
engine = _superuser_engine()
try:
with engine.begin() as conn:
conn.execute(text("SET LOCAL session_replication_role = replica"))
conn.execute(
text(
"DELETE FROM query_versions WHERE definition_id IN "
f"(SELECT id FROM query_definitions WHERE {where})"
),
{"v": value},
)
conn.execute(text(f"DELETE FROM query_definitions WHERE {where}"), {"v": value})
finally:
engine.dispose()
+920
View File
@@ -0,0 +1,920 @@
"""Query definition API tests (M04 S3): permissions, draft CRUD, publish, preview, references.
Why: these routes are the only way to maintain query drafts and freeze versions, and they
can trigger a run against a customer database, so roles, version immutability and the
no-secret/no-rows audit rules need proof.
Boundary: uses the local platform Postgres and seeded sessions like test_datasource_api;
the executor is replaced by a fake for outcome-shape tests, and the real run_query is used
only for paths that never open a socket (validation failure, disabled datasource). Rows
created here are removed afterwards (audit events are append-only and kept).
Depends on watchman.api.app, the session store and the query/datasource services.
"""
from __future__ import annotations
import json
import uuid
import pytest
from sqlalchemy import select, text
# The imported autouse fixtures (key + cleanup) must be visible in this module.
from test_datasource_api import ( # noqa: F401
ADMIN,
NAME_PREFIX,
OPERATOR,
VIEWER,
_client,
_create,
cleanup,
datasource_key,
)
from _privileged_cleanup import purge_query_rows
from watchman.auth.access import (
QUERY_PREVIEW_NODE,
QUERY_PUBLISH_NODE,
QUERY_READ_NODE,
QUERY_WRITE_NODE,
require_query_preview,
require_query_publish,
require_query_read,
require_query_write,
)
from watchman.core.config import get_settings
from watchman.core.db import get_session_factory, set_tenant
from watchman.core.errors import ForbiddenError
from watchman.models.datasource import DataSource
from watchman.models.platform import AuditEvent
from watchman.models.query import QueryDefinition, QueryVersion
from watchman.queries import QueryRunResult
from watchman.queries.result import failure
from watchman.services import queries as service
SQL = "SELECT 1 AS n WHERE :flag"
PARAM_SCHEMA = [{"name": "flag", "type": "boolean", "required": False, "default": True}]
OUTPUT_SCHEMA = [{"name": "n", "type": "integer"}]
FOREIGN_TENANT = "other-tenant-query-api-test"
@pytest.fixture(autouse=True)
def query_cleanup(cleanup): # noqa: F811
"""Remove this run's queries before the datasource cleanup (RESTRICT foreign keys)."""
yield
# query_versions is append-only for the app role, so cleanup is a superuser purge.
purge_query_rows(name_like=f"{NAME_PREFIX}%")
def _qbody(ds_id: str, **overrides) -> dict:
values = {
"name": f"{NAME_PREFIX}q-{uuid.uuid4().hex[:8]}",
"description": "synthetic query",
"datasource_id": ds_id,
"sql_template": SQL,
"param_schema": PARAM_SCHEMA,
"output_schema": OUTPUT_SCHEMA,
"allowed_identifiers": [],
"timeout_ms": 5000,
"max_rows": 50,
}
values.update(overrides)
return values
def _make(client, ds_id: str | None = None, **overrides) -> dict:
if ds_id is None:
ds_id = _create(client)["id"]
response = client.post("/queries", json=_qbody(ds_id, **overrides))
assert response.status_code == 200, response.text
return response.json()["data"]
def _db_rows(query_id: str) -> tuple[QueryDefinition, list[QueryVersion]]:
session = get_session_factory()()
try:
set_tenant(session, get_settings().tenant_id)
definition = session.scalar(
select(QueryDefinition).where(QueryDefinition.id == uuid.UUID(query_id))
)
assert definition is not None
versions = list(
session.scalars(
select(QueryVersion)
.where(QueryVersion.definition_id == definition.id)
.order_by(QueryVersion.version_no)
)
)
return definition, versions
finally:
session.close()
def _audit(query_id: str, action: str) -> list[AuditEvent]:
session = get_session_factory()()
try:
set_tenant(session, get_settings().tenant_id)
return list(
session.scalars(
select(AuditEvent).where(
AuditEvent.tenant_id == get_settings().tenant_id,
AuditEvent.action == action,
AuditEvent.payload["id"].as_string() == query_id,
)
)
)
finally:
session.close()
@pytest.fixture
def fake_run(monkeypatch: pytest.MonkeyPatch):
"""Replace the executor; records every call and returns the configured result."""
state: dict = {"calls": [], "result": QueryRunResult(status="success", message="ok")}
def _fake(session, **kwargs):
state["calls"].append(kwargs)
return state["result"]
monkeypatch.setattr(service, "run_query", _fake)
return state
# --- permission nodes and role rules ---------------------------------------------------------
def test_node_strings_and_role_rules() -> None:
assert QUERY_READ_NODE == "perm:data:emp:watchman.query.read"
assert QUERY_WRITE_NODE == "perm:data:emp:watchman.query.write"
assert QUERY_PUBLISH_NODE == "perm:data:emp:watchman.query.publish"
assert QUERY_PREVIEW_NODE == "perm:data:emp:watchman.query.preview"
checks = [
(require_query_read, QUERY_READ_NODE),
(require_query_write, QUERY_WRITE_NODE),
(require_query_publish, QUERY_PUBLISH_NODE),
(require_query_preview, QUERY_PREVIEW_NODE),
]
for check, node in checks:
check(ADMIN)
for roles in (OPERATOR, VIEWER, [], ["someone-else"]):
with pytest.raises(ForbiddenError) as raised:
check(roles)
assert raised.value.permission_node == node
ANY_ID = str(uuid.uuid4())
ROUTES = [
("GET", "/queries", None),
("POST", "/queries", {"name": "x", "datasource_id": ANY_ID, "sql_template": "SELECT 1"}),
("GET", f"/queries/{ANY_ID}", None),
("PATCH", f"/queries/{ANY_ID}", {"description": "x"}),
("POST", f"/queries/{ANY_ID}/disable", None),
("POST", f"/queries/{ANY_ID}/enable", None),
("POST", f"/queries/{ANY_ID}/versions", {"sql_template": "SELECT 1"}),
("POST", f"/queries/{ANY_ID}/versions/1/activate", None),
("GET", f"/queries/{ANY_ID}/versions", None),
("GET", f"/queries/{ANY_ID}/versions/1", None),
("POST", f"/queries/{ANY_ID}/preview", {"params": {}}),
("POST", f"/queries/{ANY_ID}/versions/1/preview", {"params": {}}),
("GET", f"/queries/{ANY_ID}/references", None),
]
@pytest.mark.parametrize(("method", "path", "payload"), ROUTES)
def test_anonymous_is_41000_without_permission_node(cleanup, method, path, payload) -> None:
response = _client(cleanup, None).request(method, path, json=payload)
assert response.status_code == 401
error = response.json()["error"]
assert error["code"] == 41000
assert "permission_node" not in error
def _node_for(method: str, path: str) -> str:
if path.endswith("/preview"):
return QUERY_PREVIEW_NODE
if path.endswith("/activate") or (
method == "POST" and (path == "/queries" or path.endswith("/versions"))
):
return QUERY_PUBLISH_NODE
if method == "GET":
return QUERY_READ_NODE
return QUERY_WRITE_NODE
@pytest.mark.parametrize("roles", [VIEWER, OPERATOR, [], ["someone-else"]])
@pytest.mark.parametrize(("method", "path", "payload"), ROUTES)
def test_non_admin_is_42000_with_node_and_nothing_changes(
cleanup, roles, method, path, payload
) -> None:
# A real definition proves a denied write cannot touch it; denial precedes any lookup.
created = _make(_client(cleanup, ADMIN))
real_path = path.replace(ANY_ID, created["id"])
body = payload
if method == "POST" and path == "/queries":
body = _qbody(created["datasource_id"])
response = _client(cleanup, roles).request(method, real_path, json=body)
assert response.status_code == 403
error = response.json()["error"]
assert error["code"] == 42000
assert error["permission_node"] == _node_for(method, path)
definition, versions = _db_rows(created["id"])
assert definition.enabled is True and definition.description == "synthetic query"
assert definition.latest_published_version_no == 1 and definition.current_version_no == 1
assert len(versions) == 1
# --- create, read, update, enable, disable ---------------------------------------------------
def test_create_get_list_and_audit(cleanup) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
body = _qbody(ds_id)
response = client.post("/queries", json=body)
assert response.status_code == 200
data = response.json()["data"]
assert response.json()["success"] is True
assert set(data) >= {
"id", "name", "description", "datasource_id", "enabled",
"current_version_no", "latest_version_no", "latest_published_version_no",
"created_at", "updated_at", "current",
}
assert "draft" not in data
assert data["enabled"] is True
assert data["current_version_no"] == 1 and data["latest_version_no"] == 1
assert data["datasource_id"] == ds_id and data["name"] == body["name"]
assert data["current"] == {
"sql_template": SQL,
"param_schema": PARAM_SCHEMA,
"output_schema": OUTPUT_SCHEMA,
"allowed_identifiers": [],
"timeout_ms": 5000,
"max_rows": 50,
}
detail = client.get(f"/queries/{data['id']}")
assert detail.status_code == 200 and detail.json()["data"] == data
listing = client.get("/queries").json()["data"]["items"]
item = next(i for i in listing if i["id"] == data["id"])
assert "draft" not in item and "current" not in item
assert item["current_version_no"] == 1
events = _audit(data["id"], "query.create")
assert len(events) == 1
assert events[0].payload == {
"id": data["id"],
"name": body["name"],
"datasource_id": ds_id,
"version_no": 1,
}
assert SQL not in json.dumps(events[0].payload)
def test_create_defaults_and_limit_cap(cleanup) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
minimal = {
"name": f"{NAME_PREFIX}min-{uuid.uuid4().hex[:6]}",
"datasource_id": ds_id,
"sql_template": "SELECT 1",
}
created = client.post("/queries", json=minimal).json()["data"]
assert created["current"]["timeout_ms"] == 10000 and created["current"]["max_rows"] == 100
assert created["current"]["param_schema"] == [] and created["description"] is None
capped = _make(client, ds_id, timeout_ms=10**9, max_rows=10**9)
assert capped["current"]["timeout_ms"] == 300000 and capped["current"]["max_rows"] == 10000
def test_create_validation(cleanup) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
bad_bodies = [
_qbody(ds_id, tenant_id="other-tenant"),
_qbody(ds_id, enabled=False),
_qbody(ds_id, latest_published_version_no=5),
_qbody(ds_id, draft_sql_template="SELECT 2"),
_qbody(ds_id, name=" "),
_qbody(ds_id, sql_template=" "),
_qbody(ds_id, sql_template=""),
_qbody(ds_id, param_schema=[{"name": "p", "type": "string", "extra": 1}]),
_qbody(ds_id, param_schema=[{"name": "p", "type": "blob"}]),
_qbody(ds_id, param_schema="nope"),
_qbody(ds_id, output_schema=[{"name": "c", "type": "string", "x": 1}]),
_qbody(ds_id, allowed_identifiers=["bad-name"]),
_qbody(ds_id, timeout_ms=0),
_qbody(ds_id, max_rows=-1),
_qbody(ds_id, max_rows=True),
_qbody(ds_id, datasource_id=str(uuid.uuid4())),
_qbody(ds_id, datasource_id="not-a-uuid"),
]
for body in bad_bodies:
response = client.post("/queries", json=body)
assert response.status_code == 400, body
assert response.json()["error"]["code"] == 40000
missing = _qbody(ds_id)
del missing["datasource_id"]
assert client.post("/queries", json=missing).status_code == 400
# Nothing leaked into storage from the rejected bodies.
names = {i["name"] for i in client.get("/queries").json()["data"]["items"]}
assert not any(b["name"] in names for b in bad_bodies if b["name"].strip())
def test_create_rejects_non_database_datasource_and_duplicate_name(cleanup) -> None:
client = _client(cleanup, ADMIN)
first = _make(client)
clash = client.post("/queries", json=_qbody(first["datasource_id"], name=first["name"]))
assert clash.status_code == 409
assert clash.json()["error"]["details"]["reason"] == "duplicate_name"
# Another tenant's datasource cannot be bound.
foreign = _foreign_datasource()
try:
response = client.post("/queries", json=_qbody(str(foreign)))
assert response.status_code == 400
assert response.json()["error"]["details"]["reason"] == "datasource_not_found"
finally:
_drop_foreign(foreign)
def test_patch_updates_metadata_only_and_content_uses_save_version(cleanup) -> None:
client = _client(cleanup, ADMIN)
created = _make(client)
qid = created["id"]
new_ds = _create(client)["id"]
new_name = f"{NAME_PREFIX}renamed-{uuid.uuid4().hex[:6]}"
# Content fields on PATCH are refused (D26): either pydantic extra-forbid or service reason.
refused = client.patch(
f"/queries/{qid}",
json={"sql_template": "SELECT 2 AS n", "max_rows": 7},
)
assert refused.status_code == 400
assert refused.json()["error"]["code"] == 40000
response = client.patch(
f"/queries/{qid}",
json={"name": new_name, "description": None, "datasource_id": new_ds},
)
assert response.status_code == 200, response.text
data = response.json()["data"]
assert data["name"] == new_name and data["description"] is None
assert data["datasource_id"] == new_ds
assert data["current"]["sql_template"] == SQL
assert data["current_version_no"] == 1
saved = client.post(
f"/queries/{qid}/versions",
json={
"sql_template": "SELECT 2 AS n",
"param_schema": [],
"output_schema": [],
"allowed_identifiers": [],
"timeout_ms": 5000,
"max_rows": 7,
},
)
assert saved.status_code == 200, saved.text
assert saved.json()["data"]["version_no"] == 2
detail = client.get(f"/queries/{qid}").json()["data"]
assert detail["current_version_no"] == 2 and detail["latest_version_no"] == 2
assert detail["current"]["sql_template"] == "SELECT 2 AS n"
assert detail["current"]["max_rows"] == 7
events = _audit(qid, "query.update")
assert len(events) == 1
assert set(events[0].payload["fields"]) == {"name", "description", "datasource_id"}
assert client.patch(f"/queries/{qid}", json={"name": new_name}).status_code == 200
assert client.patch(f"/queries/{qid}", json={}).status_code == 200
def test_patch_validation(cleanup) -> None:
client = _client(cleanup, ADMIN)
created = _make(client)
other = _make(client, created["datasource_id"])
qid = created["id"]
bad_bodies = [
{"tenant_id": "x"},
{"enabled": False},
{"version_no": 3},
{"published_by": "someone"},
{"latest_published_version_no": 9},
{"current_version_no": 2},
{"draft_sql_template": "SELECT 2"},
{"id": str(uuid.uuid4())},
{"name": None},
{"datasource_id": None},
{"sql_template": "SELECT 1"},
{"param_schema": []},
{"timeout_ms": 1000},
{"max_rows": 10},
{"datasource_id": str(uuid.uuid4())},
]
for body in bad_bodies:
response = client.patch(f"/queries/{qid}", json=body)
assert response.status_code == 400, body
assert response.json()["error"]["code"] == 40000
clash = client.patch(f"/queries/{qid}", json={"name": other["name"]})
assert clash.status_code == 409
assert clash.json()["error"]["details"]["reason"] == "duplicate_name"
assert client.get(f"/queries/{qid}").json()["data"] == created
def test_enable_disable_roundtrip_and_filter(cleanup) -> None:
client = _client(cleanup, ADMIN)
created = _make(client)
qid = created["id"]
disabled = client.post(f"/queries/{qid}/disable")
assert disabled.status_code == 200 and disabled.json()["data"]["enabled"] is False
assert client.get(f"/queries/{qid}").json()["data"]["enabled"] is False
assert client.delete(f"/queries/{qid}").status_code == 405
def ids(**params) -> list[str]:
items = client.get("/queries", params=params).json()["data"]["items"]
return [i["id"] for i in items]
assert qid in ids() and qid in ids(enabled="false") and qid not in ids(enabled="true")
enabled = client.post(f"/queries/{qid}/enable")
assert enabled.status_code == 200 and enabled.json()["data"]["enabled"] is True
assert qid in ids(enabled="true") and qid not in ids(enabled="false")
assert client.get("/queries", params={"enabled": "maybe"}).status_code == 400
assert len(_audit(qid, "query.disable")) == 1 and len(_audit(qid, "query.enable")) == 1
def test_list_supports_name_filter_sort_and_pagination(cleanup) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
suffix = uuid.uuid4().hex[:6]
first = _make(client, ds_id, name=f"{NAME_PREFIX}alpha-{suffix}")
second = _make(client, ds_id, name=f"{NAME_PREFIX}beta-{suffix}")
page = client.get(
"/queries",
params={
"name": suffix,
"sort_by": "name",
"sort_order": "asc",
"page": 1,
"page_size": 1,
},
)
assert page.status_code == 200
body = page.json()["data"]
assert body["total"] >= 2 and body["page"] == 1 and body["page_size"] == 1
assert len(body["items"]) == 1
assert body["items"][0]["id"] == first["id"]
page2 = client.get(
"/queries",
params={"name": suffix, "sort_by": "name", "sort_order": "asc", "page": 2, "page_size": 1},
).json()["data"]
assert page2["items"][0]["id"] == second["id"]
assert client.get("/queries", params={"sort_by": "nope"}).status_code == 400
assert client.get("/queries", params={"page_size": 0}).status_code == 400
def test_unknown_foreign_and_malformed_ids_are_404(cleanup) -> None:
client = _client(cleanup, ADMIN)
foreign_ds = _foreign_datasource()
foreign_q = _foreign_query(foreign_ds)
try:
for path in (
f"/queries/{uuid.uuid4()}",
f"/queries/{foreign_q}",
f"/queries/{foreign_q}/versions",
f"/queries/{foreign_q}/references",
"/queries/not-a-uuid",
):
assert client.get(path).status_code == 404, path
assert client.patch(f"/queries/{foreign_q}", json={"description": "x"}).status_code == 404
assert client.post(f"/queries/{foreign_q}/disable").status_code == 404
assert client.post(
f"/queries/{foreign_q}/versions", json={"sql_template": "SELECT 1"}
).status_code == 404
assert client.post(f"/queries/{foreign_q}/versions/1/activate").status_code == 404
assert client.post(f"/queries/{foreign_q}/preview", json={"params": {}}).status_code == 404
assert foreign_q not in [i["id"] for i in client.get("/queries").json()["data"]["items"]]
finally:
_drop_foreign(foreign_ds)
# --- versions and activate -------------------------------------------------------------------
def test_create_has_v1_and_save_version_increments(cleanup) -> None:
client = _client(cleanup, ADMIN)
created = _make(client)
qid = created["id"]
listing0 = client.get(f"/queries/{qid}/versions").json()["data"]
assert [i["version_no"] for i in listing0["items"]] == [1]
v1 = client.get(f"/queries/{qid}/versions/1").json()["data"]
assert v1["version_no"] == 1 and v1["definition_id"] == qid
assert v1["published_by"] == "worker" and v1["sql_template"] == SQL
assert client.get(f"/queries/{qid}").json()["data"]["current_version_no"] == 1
second = client.post(
f"/queries/{qid}/versions",
json={
"sql_template": "SELECT 99 AS n",
"param_schema": [],
"output_schema": [],
"allowed_identifiers": [],
"timeout_ms": 5000,
"max_rows": 3,
},
)
assert second.status_code == 200, second.text
v2 = second.json()["data"]
assert v2["version_no"] == 2 and v2["sql_template"] == "SELECT 99 AS n"
assert client.get(f"/queries/{qid}/versions/1").json()["data"] == v1
detail = client.get(f"/queries/{qid}").json()["data"]
assert detail["current_version_no"] == 2 and detail["latest_version_no"] == 2
listing = client.get(f"/queries/{qid}/versions").json()["data"]
assert [i["version_no"] for i in listing["items"]] == [2, 1]
assert all("sql_template" not in i for i in listing["items"])
definition, versions = _db_rows(qid)
assert definition.current_version_no == 2 and definition.latest_published_version_no == 2
assert [v.version_no for v in versions] == [1, 2]
events = _audit(qid, "query.save_version")
assert [e.payload["version_no"] for e in events] == [2]
def test_activate_switches_current_without_new_version(cleanup) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
client.post(
f"/queries/{qid}/versions",
json={
"sql_template": "SELECT 99 AS n",
"param_schema": [],
"output_schema": [],
"allowed_identifiers": [],
"timeout_ms": 5000,
"max_rows": 3,
},
)
activated = client.post(f"/queries/{qid}/versions/1/activate")
assert activated.status_code == 200, activated.text
data = activated.json()["data"]
assert data["current_version_no"] == 1 and data["latest_version_no"] == 2
assert data["current"]["sql_template"] == SQL
_, versions = _db_rows(qid)
assert len(versions) == 2
events = _audit(qid, "query.activate_version")
assert len(events) == 1 and events[0].payload["version_no"] == 1
def test_disabled_query_can_still_save_version_and_version_reads_work(cleanup) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
client.post(f"/queries/{qid}/disable")
saved = client.post(
f"/queries/{qid}/versions",
json={"sql_template": "SELECT 2", "param_schema": [], "output_schema": []},
)
assert saved.status_code == 200
assert client.get(f"/queries/{qid}/versions/2").status_code == 200
def test_save_version_refuses_blank_sql(cleanup) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
response = client.post(
f"/queries/{qid}/versions",
json={"sql_template": " ", "param_schema": [], "output_schema": []},
)
assert response.status_code == 400
definition, versions = _db_rows(qid)
assert definition.latest_published_version_no == 1 and len(versions) == 1
def test_version_row_immutable_and_patch_refuses_version_fields(cleanup) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
v1 = client.get(f"/queries/{qid}/versions/1").json()["data"]
for method in ("PATCH", "PUT", "DELETE"):
response = client.request(method, f"/queries/{qid}/versions/1", json={"sql_template": "x"})
assert response.status_code in (404, 405), method
for body in (
{"version_no": 1},
{"published_by": "mallory"},
{"published_at": "2020-01-01T00:00:00Z"},
{"latest_published_version_no": 1},
{"current_version_no": 1},
{"versions": [{"sql_template": "x"}]},
):
assert client.patch(f"/queries/{qid}", json=body).status_code == 400, body
assert client.get(f"/queries/{qid}/versions/1").json()["data"] == v1
_, versions = _db_rows(qid)
assert len(versions) == 1 and versions[0].sql_template == SQL
def test_version_lookup_validation(cleanup) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
assert client.get(f"/queries/{qid}/versions/2").status_code == 404
assert client.get(f"/queries/{qid}/versions/0").status_code == 404
assert client.get(f"/queries/{qid}/versions/abc").status_code == 400
assert client.post(f"/queries/{qid}/versions/2/preview", json={"params": {}}).status_code == 404
assert client.post(f"/queries/{qid}/versions/9/activate").status_code == 404
# --- preview ---------------------------------------------------------------------------------
def test_preview_outcomes_have_distinct_shapes(cleanup, fake_run) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
path = f"/queries/{qid}/preview"
fake_run["result"] = QueryRunResult(
status="success", message="query succeeded", columns=["n"], rows=[{"n": 1}, {"n": 2}]
)
ok = client.post(path, json={"params": {"flag": True}})
assert ok.status_code == 200 and ok.json()["success"] is True
data = ok.json()["data"]
assert data == {
"id": qid, "version_no": 1, "source": "current", "status": "success",
"message": "query succeeded", "columns": ["n"], "rows": [{"n": 1}, {"n": 2}],
"row_count": 2, "masked_columns": [],
} # fmt: skip
fake_run["result"] = QueryRunResult(status="empty", message="query returned no rows", columns=["n"])
empty = client.post(path, json={"params": {}}).json()["data"]
assert empty["status"] == "empty" and empty["rows"] == [] and empty["row_count"] == 0
assert "failure_kind" not in empty and "details" not in empty
fake_run["result"] = QueryRunResult(
status="illegal_type",
message="query result violates the output schema",
columns=["n"],
details={"fields": [{"field": "n", "expected": "integer", "actual": "str", "row": 0}]},
)
illegal = client.post(path, json={"params": {}}).json()["data"]
assert illegal["status"] == "illegal_type"
assert illegal["details"]["fields"][0]["expected"] == "integer"
assert "rows" not in illegal and "failure_kind" not in illegal
fake_run["result"] = failure("timeout", "query timed out", category="timeout")
failed = client.post(path, json={"params": {}})
assert failed.status_code == 200 # a failed run is a result, not an API error
failed_data = failed.json()["data"]
assert failed_data["status"] == "failure" and failed_data["failure_kind"] == "timeout"
assert "rows" not in failed_data and failed_data["details"] == {"category": "timeout"}
# The executor got the draft content and the bound datasource, never a tenant.
call = fake_run["calls"][0]
assert call["sql_template"] == SQL and call["params"] == {"flag": True}
assert call["timeout_ms"] == 5000 and call["max_rows"] == 50
assert call["param_schema"] == PARAM_SCHEMA and call["output_schema"] == OUTPUT_SCHEMA
assert "tenant_id" not in call
def test_preview_body_is_optional_and_strict(cleanup, fake_run) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
assert client.post(f"/queries/{qid}/preview").status_code == 200
assert fake_run["calls"][-1]["params"] == {}
for body in ({"sql": "DROP TABLE x"}, {"params": [1]}, {"params": {}, "datasource_id": "x"}):
assert client.post(f"/queries/{qid}/preview", json=body).status_code == 400, body
assert len(fake_run["calls"]) == 1
def test_preview_masks_sensitive_columns(cleanup, fake_run) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
fake_run["result"] = QueryRunResult(
status="success",
message="query succeeded",
columns=["user_name", "Password", "phone_no", "note"],
rows=[
{"user_name": "a", "Password": "hunter2", "phone_no": "13800000000", "note": None},
{"user_name": "b", "Password": None, "phone_no": "13900000000", "note": "x"},
],
)
data = client.post(f"/queries/{qid}/preview", json={"params": {}}).json()["data"]
assert data["masked_columns"] == ["Password", "phone_no"]
assert data["rows"][0] == {"user_name": "a", "Password": "***", "phone_no": "***", "note": None}
assert data["rows"][1] == {"user_name": "b", "Password": None, "phone_no": "***", "note": "x"}
assert "hunter2" not in json.dumps(data)
def test_preview_audit_has_only_id_version_and_status(cleanup, fake_run) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
fake_run["result"] = QueryRunResult(
status="success", message="secret-row-message", columns=["n"], rows=[{"n": "ROWVALUE-123"}]
)
assert client.post(f"/queries/{qid}/preview", json={"params": {"flag": True}}).status_code == 200
assert client.post(f"/queries/{qid}/versions/1/preview", json={"params": {}}).status_code == 200
fake_run["result"] = failure("sql_error", "query failed")
assert client.post(f"/queries/{qid}/preview", json={"params": {}}).status_code == 200
events = sorted(_audit(qid, "query.preview"), key=lambda e: e.id)
payloads = [e.payload for e in events]
assert len(payloads) == 3
assert payloads.count({"id": qid, "status": "success", "version_no": 1}) == 2
assert {"id": qid, "status": "failure", "version_no": 1} in payloads
for event in events:
assert set(event.payload) <= {"id", "status", "version_no"}
dumped = json.dumps(event.payload) + event.idempotency_key
assert "ROWVALUE" not in dumped and "secret-row-message" not in dumped
assert "SELECT" not in dumped and "flag" not in dumped
def test_preview_version_runs_frozen_content_not_current(cleanup, fake_run) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
client.post(
f"/queries/{qid}/versions",
json={
"sql_template": "SELECT 99 AS n",
"param_schema": [],
"output_schema": [],
"allowed_identifiers": [],
"timeout_ms": 5000,
"max_rows": 2,
},
)
fake_run["result"] = QueryRunResult(status="empty", message="query returned no rows")
response = client.post(f"/queries/{qid}/versions/1/preview", json={"params": {"flag": False}})
assert response.status_code == 200
data = response.json()["data"]
assert data["version_no"] == 1 and data["source"] == "version" and data["status"] == "empty"
call = fake_run["calls"][-1]
assert call["sql_template"] == SQL and call["max_rows"] == 50
assert call["params"] == {"flag": False}
client.post(f"/queries/{qid}/preview", json={"params": {}})
assert fake_run["calls"][-1]["sql_template"] == "SELECT 99 AS n"
assert fake_run["calls"][-1]["max_rows"] == 2
def test_disabled_definition_refuses_preview_without_running(cleanup, fake_run) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
client.post(f"/queries/{qid}/disable")
for path in (f"/queries/{qid}/preview", f"/queries/{qid}/versions/1/preview"):
response = client.post(path, json={"params": {}})
assert response.status_code == 409
error = response.json()["error"]
assert error["code"] == 40000 and error["details"]["reason"] == "disabled"
assert fake_run["calls"] == []
assert _audit(qid, "query.preview") == []
# Still readable, and previewable again once enabled.
assert client.get(f"/queries/{qid}").status_code == 200
client.post(f"/queries/{qid}/enable")
assert client.post(f"/queries/{qid}/preview", json={"params": {}}).status_code == 200
def test_preview_with_real_executor_without_network(cleanup, monkeypatch) -> None:
"""Validation failure and a disabled datasource come back as results, with no socket."""
def _boom(*_a, **_k):
raise AssertionError("network must not be used")
monkeypatch.setattr("socket.create_connection", _boom)
monkeypatch.setattr("watchman.queries.drivers.fetch_rows", _boom)
client = _client(cleanup, ADMIN)
created = _make(client)
qid = created["id"]
unknown = client.post(f"/queries/{qid}/preview", json={"params": {"nope": 1}})
assert unknown.status_code == 200
data = unknown.json()["data"]
assert data["status"] == "failure" and data["failure_kind"] == "validation"
assert data["details"]["reason"] == "unknown_param"
client.post(f"/datasources/{created['datasource_id']}/disable")
blocked = client.post(f"/queries/{qid}/preview", json={"params": {}})
assert blocked.status_code == 200
blocked_data = blocked.json()["data"]
assert blocked_data["status"] == "failure" and blocked_data["failure_kind"] == "disabled"
assert len(_audit(qid, "query.preview")) == 2
def test_preview_on_sqlserver_datasource_is_refused_without_a_connection(
cleanup, monkeypatch
) -> None:
"""SQL Server has no server-enforced read-only session: preview never reaches a driver."""
def _boom(*_a, **_k):
raise AssertionError("no connection may be opened for sqlserver")
monkeypatch.setattr("socket.create_connection", _boom)
monkeypatch.setattr("pymssql.connect", _boom)
monkeypatch.setattr("watchman.queries.drivers.fetch_rows", _boom)
client = _client(cleanup, ADMIN)
ds_id = _create(client, engine="sqlserver", port=1433)["id"]
qid = _make(client, ds_id, sql_template="SELECT 1 AS n WHERE :flag")["id"]
response = client.post(f"/queries/{qid}/preview", json={"params": {}})
assert response.status_code == 200
data = response.json()["data"]
assert data["status"] == "failure"
assert data["failure_kind"] == "engine_readonly_unsupported"
assert "rows" not in data or not data["rows"]
assert "SQL Server" in data["message"]
assert len(_audit(qid, "query.preview")) == 1
# --- references ------------------------------------------------------------------------------
def test_query_references_are_stably_empty(cleanup) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
response = client.get(f"/queries/{qid}/references")
assert response.status_code == 200
assert response.json()["data"] == {"id": qid, "items": []}
def test_datasource_references_list_queries(cleanup) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
other_ds = _create(client)["id"]
assert client.get(f"/datasources/{ds_id}/references").json()["data"] == {
"id": ds_id,
"items": [],
}
a = _make(client, ds_id, name=f"{NAME_PREFIX}ref-b")
b = _make(client, ds_id, name=f"{NAME_PREFIX}ref-a")
_make(client, other_ds)
data = client.get(f"/datasources/{ds_id}/references").json()["data"]
assert data["id"] == ds_id
assert data["items"] == [
{"type": "query", "id": b["id"], "name": b["name"], "enabled": True},
{"type": "query", "id": a["id"], "name": a["name"], "enabled": True},
]
client.post(f"/queries/{a['id']}/disable")
items = client.get(f"/datasources/{ds_id}/references").json()["data"]["items"]
assert {i["id"]: i["enabled"] for i in items} == {a["id"]: False, b["id"]: True}
# Moving a query to another datasource moves the reference with it.
client.patch(f"/queries/{b['id']}", json={"datasource_id": other_ds})
items = client.get(f"/datasources/{ds_id}/references").json()["data"]["items"]
assert [i["id"] for i in items] == [a["id"]]
assert b["id"] in [
i["id"] for i in client.get(f"/datasources/{other_ds}/references").json()["data"]["items"]
]
def test_datasource_references_ignore_other_tenants(cleanup) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
foreign_ds = _foreign_datasource()
foreign_q = _foreign_query(foreign_ds)
try:
items = client.get(f"/datasources/{ds_id}/references").json()["data"]["items"]
assert foreign_q not in [i["id"] for i in items]
finally:
_drop_foreign(foreign_ds)
# --- foreign tenant helpers ------------------------------------------------------------------
def _foreign_datasource() -> uuid.UUID:
session = get_session_factory()()
try:
set_tenant(session, FOREIGN_TENANT)
row = DataSource(
tenant_id=FOREIGN_TENANT,
name=f"{NAME_PREFIX}foreign-ds",
kind="database",
engine="postgresql",
host="h.invalid",
port=5432,
database_name="d",
username="u",
secret_ciphertext="opaque",
)
session.add(row)
session.commit()
return row.id
finally:
session.close()
def _foreign_query(datasource_id: uuid.UUID) -> str:
session = get_session_factory()()
try:
set_tenant(session, FOREIGN_TENANT)
row = QueryDefinition(
tenant_id=FOREIGN_TENANT,
name=f"{NAME_PREFIX}foreign-q",
datasource_id=datasource_id,
draft_sql_template="SELECT 1",
)
session.add(row)
session.commit()
return str(row.id)
finally:
session.close()
def _drop_foreign(datasource_id: uuid.UUID) -> None:
session = get_session_factory()()
purge_query_rows(datasource_id=datasource_id) # versions are append-only for the app role
try:
set_tenant(session, FOREIGN_TENANT)
session.execute(text("DELETE FROM data_sources WHERE id = :d"), {"d": datasource_id})
session.commit()
finally:
session.close()
@@ -0,0 +1,964 @@
"""Read-only query executor tests (M04 S2): binding, whitelist, outcomes, circuit accounting.
Why: this is the only code that sends user SQL to a customer database, so injection
resistance, the usability gate and the empty/illegal_type/failure split need proof.
Boundary: template tests need no database; run_query tests use the platform Postgres for
datasource rows and replace the driver with fakes; the live tests run real statements against
WATCHMAN_TEST_PG_* and skip when it is not configured. Rows created here are removed by the
shared cleanup fixture from test_datasource_api (audit events are append-only and kept).
"""
from __future__ import annotations
import json
import uuid
from datetime import datetime, timedelta, timezone
import pytest
from sqlalchemy import select
# The imported autouse fixtures (key + cleanup) must be visible in this module.
from test_datasource_api import NAME_PREFIX, cleanup, datasource_key # noqa: F401
from watchman.core.config import get_settings, merge_layered_env, reload_settings
from watchman.core.db import get_session_factory, reset_engine, set_tenant
from watchman.core.errors import NotFoundError, ValidationError
from watchman.datasources import ProbeCategory
from watchman.models.datasource import DataSource
from watchman.queries import drivers, run_query
from watchman.queries.drivers import ConnectFailure, FetchResult, QueryFailure
from watchman.queries.template import prepare_query
from watchman.services import datasources as service
PARAMS = [{"name": "object_id", "type": "string", "required": True}]
INJECTION = "x'; DROP TABLE data_sources; --"
# --- template preparation (no database) ---------------------------------------------------
def _prepare(sql: str, *, engine: str = "postgresql", schema=None, allowed=None, params=None):
return prepare_query(
engine=engine,
sql_template=sql,
param_schema=PARAMS if schema is None else schema,
allowed_identifiers=[] if allowed is None else allowed,
params={} if params is None else params,
)
def _reason(excinfo) -> str:
return excinfo.value.details["reason"]
def test_param_with_sql_fragment_is_bound_not_spliced() -> None:
prepared = _prepare(
"SELECT * FROM t WHERE id = :object_id", params={"object_id": INJECTION}
)
assert prepared.sql == "SELECT * FROM t WHERE id = %(object_id)s"
assert prepared.params == {"object_id": INJECTION}
assert "DROP" not in prepared.sql
def test_repeated_param_and_casts_and_literals() -> None:
prepared = _prepare(
"SELECT ':object_id' AS lit, x::int, :object_id AS a, :object_id AS b -- :object_id\n",
params={"object_id": "1"},
)
assert prepared.sql.count("%(object_id)s") == 2
assert "':object_id'" in prepared.sql and "x::int" in prepared.sql
assert prepared.params == {"object_id": "1"}
def test_percent_is_escaped_only_when_binding() -> None:
bound = _prepare("SELECT 'a%b' AS s, :object_id", params={"object_id": "1"})
assert "'a%%b'" in bound.sql
plain = _prepare("SELECT 'a%b' AS s", schema=[])
assert plain.sql == "SELECT 'a%b' AS s" and plain.params is None
def test_unknown_param_rejected() -> None:
with pytest.raises(ValidationError) as exc:
_prepare("SELECT :object_id", params={"object_id": "1", "extra": "2"})
assert _reason(exc) == "unknown_param"
assert exc.value.details["fields"] == ["extra"]
def test_missing_required_and_default_for_optional() -> None:
with pytest.raises(ValidationError) as exc:
_prepare("SELECT :object_id")
assert _reason(exc) == "missing_param"
schema = [
{"name": "n", "type": "integer", "required": False, "default": 7},
{"name": "m", "type": "integer", "required": False},
]
prepared = _prepare("SELECT :n, :m", schema=schema)
assert prepared.params == {"n": 7, "m": None}
@pytest.mark.parametrize(
("type_", "value"),
[
("integer", "1"),
("integer", True),
("number", "1.5"),
("boolean", 1),
("string", 5),
("datetime", "not-a-date"),
],
)
def test_param_type_mismatch_rejected(type_, value) -> None:
schema = [{"name": "v", "type": type_}]
with pytest.raises(ValidationError) as exc:
_prepare("SELECT :v", schema=schema, params={"v": value})
assert _reason(exc) == "param_type_mismatch"
def test_datetime_string_is_parsed() -> None:
schema = [{"name": "v", "type": "datetime"}]
prepared = _prepare("SELECT :v", schema=schema, params={"v": "2030-01-02T03:04:05+00:00"})
assert prepared.params["v"] == datetime(2030, 1, 2, 3, 4, 5, tzinfo=timezone.utc)
def test_undeclared_placeholder_rejected() -> None:
with pytest.raises(ValidationError) as exc:
_prepare("SELECT :nope", params={"object_id": "1"})
assert _reason(exc) == "undeclared_param"
@pytest.mark.parametrize(
"schema",
[
[{"name": "a", "type": "string", "bogus": 1}],
[{"name": "a", "type": "blob"}],
[{"name": "a", "type": "string"}, {"name": "a", "type": "string"}],
[{"name": "1bad", "type": "string"}],
[{"name": "a", "type": "integer", "default": "x"}],
{"name": "a"},
],
)
def test_bad_param_schema_rejected(schema) -> None:
with pytest.raises(ValidationError):
_prepare("SELECT 1", schema=schema)
def test_identifier_whitelist() -> None:
prepared = _prepare(
"SELECT * FROM {{orders}} WHERE id = :object_id",
allowed=["orders"],
params={"object_id": "1"},
)
assert prepared.sql == 'SELECT * FROM "orders" WHERE id = %(object_id)s'
mysql = _prepare("SELECT * FROM {{ orders }}", engine="mysql", schema=[], allowed=["orders"])
assert mysql.sql == "SELECT * FROM `orders`"
mssql = _prepare("SELECT * FROM {{orders}}", engine="sqlserver", schema=[], allowed=["orders"])
assert mssql.sql == "SELECT * FROM [orders]"
@pytest.mark.parametrize("allowed", [[], ["other"]])
def test_identifier_not_in_whitelist_rejected(allowed) -> None:
with pytest.raises(ValidationError) as exc:
_prepare("SELECT * FROM {{orders}}", schema=[], allowed=allowed)
assert _reason(exc) == "identifier_not_allowed"
@pytest.mark.parametrize("name", ["a-b", "a b", '"x"', "1a", "a;drop", "a.b", ""])
def test_identifier_must_match_pattern_even_if_listed(name) -> None:
with pytest.raises(ValidationError):
_prepare("SELECT * FROM {{" + name + "}}", schema=[], allowed=[name])
def test_identifier_in_literal_is_not_a_placeholder() -> None:
prepared = _prepare("SELECT '{{orders}}' AS s", schema=[])
assert prepared.sql == "SELECT '{{orders}}' AS s"
def test_param_value_can_never_become_an_identifier() -> None:
# A caller value containing the placeholder syntax stays a bound value.
prepared = _prepare("SELECT :object_id", params={"object_id": "{{orders}}"})
assert prepared.params == {"object_id": "{{orders}}"}
@pytest.mark.parametrize(
"sql",
[
"SELECT 1; DROP TABLE x",
"SELECT 1;; SELECT 2",
"SELECT 1; SELECT :object_id",
"SELECT 'unterminated",
"SELECT 1 /* open",
],
)
def test_non_single_or_broken_template_rejected(sql) -> None:
with pytest.raises(ValidationError):
_prepare(sql, params={"object_id": "1"})
def test_trailing_semicolon_and_comment_allowed() -> None:
assert _prepare("SELECT 1 ; -- done\n", schema=[]).sql == "SELECT 1 -- done"
def test_semicolon_inside_literal_is_fine() -> None:
assert _prepare("SELECT 'a;b'", schema=[]).sql == "SELECT 'a;b'"
def test_dollar_quote_hides_placeholders_on_postgres() -> None:
sql = "SELECT $$ :nope ; {{x}} $$ AS s"
assert _prepare(sql, schema=[]).sql == sql
# --- run_query with a fake driver ---------------------------------------------------------
def _session():
reload_settings()
session = get_session_factory()()
set_tenant(session, get_settings().tenant_id)
return session
def _make_datasource(session, **overrides) -> str:
row = service.create_datasource(
session,
name=f"{NAME_PREFIX}{uuid.uuid4().hex[:10]}",
description=None,
kind="database",
engine=overrides.pop("engine", "postgresql"),
host="127.0.0.1",
port=5432,
database_name="synthetic",
username="synthetic_user",
password="synthetic-pw-not-a-credential",
read_only_intent=True,
)
for key, value in overrides.items():
setattr(row, key, value)
session.commit()
return str(row.id)
def _stored(datasource_id: str) -> DataSource:
session = _session()
try:
row = session.scalar(select(DataSource).where(DataSource.id == uuid.UUID(datasource_id)))
assert row is not None
return row
finally:
session.close()
class FakeFetch:
"""Replaces drivers.fetch_rows; records the call; returns or raises the queued outcome."""
def __init__(self, outcome) -> None:
self.outcome = outcome
self.calls: list[dict] = []
def __call__(self, target, sql, params, **kwargs):
self.calls.append({"target": target, "sql": sql, "params": params, **kwargs})
if isinstance(self.outcome, BaseException):
raise self.outcome
return self.outcome
def _install(monkeypatch, outcome) -> FakeFetch:
fake = FakeFetch(outcome)
monkeypatch.setattr(drivers, "fetch_rows", fake)
return fake
def _run(session, datasource_id: str, **overrides):
kwargs = dict(
datasource_id=datasource_id,
sql_template="SELECT object_id, v FROM t WHERE object_id = :object_id",
param_schema=PARAMS,
output_schema=[{"name": "object_id", "type": "string"}, {"name": "v", "type": "number"}],
allowed_identifiers=[],
params={"object_id": "A1"},
timeout_ms=5000,
max_rows=10,
)
kwargs.update(overrides)
return run_query(session, **kwargs)
ROWS = FetchResult(columns=["object_id", "v"], rows=[("A1", 1.5), ("A2", 2)])
def test_success_returns_json_serializable_rows(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session)
fake = _install(monkeypatch, ROWS)
result = _run(session, ds)
assert result.status == "success" and result.failure_kind is None
assert result.columns == ["object_id", "v"]
assert result.rows == [{"object_id": "A1", "v": 1.5}, {"object_id": "A2", "v": 2}]
json.dumps(result.rows)
call = fake.calls[0]
assert call["sql"] == "SELECT object_id, v FROM t WHERE object_id = %(object_id)s"
assert call["params"] == {"object_id": "A1"}
assert call["limit"] == 11 and call["timeout_ms"] == 5000
# The decrypted password reaches the driver target only, never the result.
assert call["target"].password == "synthetic-pw-not-a-credential"
assert "synthetic-pw" not in repr(result)
session.close()
def test_sql_fragment_param_reaches_driver_only_as_a_bound_value(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session)
fake = _install(monkeypatch, ROWS)
_run(session, ds, params={"object_id": INJECTION})
call = fake.calls[0]
assert "DROP" not in call["sql"]
assert call["params"] == {"object_id": INJECTION}
session.close()
def test_empty_illegal_type_and_failure_are_distinct(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session)
_install(monkeypatch, FetchResult(columns=["object_id", "v"], rows=[]))
empty = _run(session, ds)
_install(monkeypatch, FetchResult(columns=["object_id", "v"], rows=[("A1", "not-a-number")]))
illegal = _run(session, ds)
_install(monkeypatch, QueryFailure("sql_error", details={"sqlstate": "42601"}))
failed = _run(session, ds)
assert (empty.status, illegal.status, failed.status) == ("empty", "illegal_type", "failure")
assert empty.failure_kind is None and empty.rows == [] and empty.columns == ["object_id", "v"]
assert illegal.failure_kind is None and illegal.rows == []
assert illegal.details["fields"] == [
{"field": "v", "expected": "number", "actual": "str", "row": 0}
]
assert "not-a-number" not in json.dumps(illegal.details)
assert failed.failure_kind == "sql_error" and failed.rows == []
session.close()
def test_null_values_and_unlisted_columns_pass_type_check(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session)
_install(monkeypatch, FetchResult(columns=["object_id", "v", "extra"], rows=[("A1", None, {})]))
result = _run(session, ds)
assert result.status == "success"
assert result.rows == [{"object_id": "A1", "v": None, "extra": "{}"}]
session.close()
def test_row_limit_exceeded_is_a_failure_without_rows(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session)
_install(monkeypatch, FetchResult(columns=["object_id", "v"], rows=[("A", 1)] * 3))
result = _run(session, ds, max_rows=2)
assert result.status == "failure" and result.failure_kind == "limit_exceeded"
assert result.rows == [] and result.details == {"max_rows": 2}
session.close()
def test_limits_are_capped_and_invalid_limits_rejected(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session)
fake = _install(monkeypatch, ROWS)
_run(session, ds, timeout_ms=10**9, max_rows=10**9)
assert fake.calls[0]["timeout_ms"] == 300000 and fake.calls[0]["limit"] == 10001
for bad in (0, -1, True, "5"):
result = _run(session, ds, timeout_ms=bad)
assert result.failure_kind == "validation"
assert result.details["reason"] == "limit_invalid"
assert len(fake.calls) == 1
session.close()
def test_validation_failures_never_connect(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session)
fake = _install(monkeypatch, AssertionError("must not connect"))
unknown = _run(session, ds, params={"object_id": "A1", "extra": 1})
not_listed = _run(
session, ds, sql_template="SELECT * FROM {{orders}}", param_schema=[], params={}
)
empty_list = _run(
session,
ds,
sql_template="SELECT * FROM {{orders}}",
param_schema=[],
params={},
allowed_identifiers=[],
)
missing = _run(session, ds, params={})
bad_output = _run(session, ds, output_schema=[{"name": "v", "type": "blob"}])
assert [r.failure_kind for r in (unknown, not_listed, empty_list, missing, bad_output)] == [
"validation"
] * 5
assert unknown.details["reason"] == "unknown_param"
assert not_listed.details["reason"] == "identifier_not_allowed"
assert empty_list.details["reason"] == "identifier_not_allowed"
assert missing.details["reason"] == "missing_param"
assert fake.calls == []
session.close()
def test_whitelisted_identifier_is_quoted_not_bound(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session)
fake = _install(monkeypatch, ROWS)
_run(
session,
ds,
sql_template="SELECT * FROM {{orders}} WHERE object_id = :object_id",
allowed_identifiers=["orders"],
)
assert fake.calls[0]["sql"] == 'SELECT * FROM "orders" WHERE object_id = %(object_id)s'
assert fake.calls[0]["params"] == {"object_id": "A1"}
session.close()
def test_disabled_datasource_is_refused_without_running_sql(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session, enabled=False)
fake = _install(monkeypatch, AssertionError("must not connect"))
result = _run(session, ds)
assert result.status == "failure" and result.failure_kind == "disabled"
assert result.details["reason"] == "disabled"
assert fake.calls == []
session.close()
@pytest.mark.parametrize(
"sql",
[
"SELECT object_id, v FROM t WHERE object_id = :object_id",
"UPDATE t SET v = 0 WHERE object_id = :object_id",
"DELETE FROM t WHERE object_id = :object_id",
"EXEC sp_write_everything",
],
)
def test_sqlserver_run_is_refused_before_any_connection_or_secret_read(
monkeypatch, sql
) -> None:
"""SQL Server has no server-enforced read-only session, so no template ever runs on it.
The refusal does not depend on the statement text: a SELECT is refused exactly like a write.
"""
import pymssql
def _no_write_path(*_a, **_k):
raise AssertionError("sqlserver must not open a connection or read the secret")
session = _session()
ds = _make_datasource(session, engine="sqlserver")
fake = _install(monkeypatch, AssertionError("must not connect"))
monkeypatch.setattr(pymssql, "connect", _no_write_path)
monkeypatch.setattr(service, "build_probe_target", _no_write_path)
result = _run(session, ds, sql_template=sql)
assert result.status == "failure"
assert result.failure_kind == "engine_readonly_unsupported"
assert result.details["reason"] == "engine_readonly_unsupported"
assert "SQL Server" in result.message and "read-only" in result.message
assert result.rows == [] and result.columns == []
assert fake.calls == []
# Not a connectivity problem: the circuit stays untouched.
assert _stored(ds).circuit_failure_count == 0
session.close()
def test_sqlserver_fetch_rows_has_no_runner_and_opens_nothing(monkeypatch) -> None:
import pymssql
from watchman.datasources import UnsupportedDataSourceError
def _forbidden(*_a, **_k):
raise AssertionError("pymssql.connect must not be called")
monkeypatch.setattr(pymssql, "connect", _forbidden)
assert "sqlserver" not in drivers._RUNNERS
with pytest.raises(UnsupportedDataSourceError):
drivers.fetch_rows(
_target("sqlserver"), "UPDATE t SET v = 1", None, timeout_ms=1000, limit=2, connect_timeout=1
)
def test_open_circuit_is_refused_without_running_sql(monkeypatch) -> None:
session = _session()
ds = _make_datasource(
session,
circuit_state="open",
circuit_opened_at=datetime.now(timezone.utc) - timedelta(seconds=5),
)
fake = _install(monkeypatch, AssertionError("must not connect"))
result = _run(session, ds)
assert result.failure_kind == "circuit_open"
assert result.details["reason"] == "circuit_open"
assert "circuit_open_until" in result.details
assert fake.calls == []
session.close()
def test_elapsed_circuit_cooldown_lets_the_run_through(monkeypatch) -> None:
session = _session()
ds = _make_datasource(
session,
circuit_state="open",
circuit_opened_at=datetime.now(timezone.utc) - timedelta(hours=2),
)
fake = _install(monkeypatch, ROWS)
assert _run(session, ds).status == "success"
assert len(fake.calls) == 1
assert _stored(ds).circuit_state == "closed"
session.close()
def test_unknown_datasource_propagates_not_found(monkeypatch) -> None:
session = _session()
_install(monkeypatch, AssertionError("must not connect"))
with pytest.raises(NotFoundError):
_run(session, str(uuid.uuid4()))
session.close()
@pytest.mark.parametrize(
("category", "kind"),
[
(ProbeCategory.AUTH_FAILED, "auth_failed"),
(ProbeCategory.TIMEOUT, "timeout"),
(ProbeCategory.UNREACHABLE, "unreachable"),
(ProbeCategory.REJECTED, "rejected"),
],
)
def test_connection_failures_are_classified_and_recorded(monkeypatch, category, kind) -> None:
session = _session()
ds = _make_datasource(session)
_install(monkeypatch, ConnectFailure(category))
result = _run(session, ds)
assert result.status == "failure" and result.failure_kind == kind
assert result.details["category"] == category.value
stored = _stored(ds)
assert stored.circuit_failure_count == 1
assert stored.circuit_state == "closed"
# No saved-connection test ran, so last_test_* is untouched.
assert stored.last_test_category is None and stored.last_test_at is None
session.close()
def test_repeated_connection_failures_open_the_circuit_then_block(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session, circuit_failure_threshold=2)
fake = _install(monkeypatch, ConnectFailure(ProbeCategory.UNREACHABLE))
first = _run(session, ds)
second = _run(session, ds)
third = _run(session, ds)
assert first.details["circuit_opened"] is False
assert second.details["circuit_opened"] is True
assert third.failure_kind == "circuit_open"
assert len(fake.calls) == 2 # the third never reached the driver
assert _stored(ds).circuit_state == "open"
session.close()
def test_sql_and_statement_timeout_failures_do_not_touch_the_circuit(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session, circuit_failure_threshold=1)
_install(monkeypatch, QueryFailure("sql_error", details={"sqlstate": "42601"}))
sql_error = _run(session, ds)
_install(monkeypatch, QueryFailure("timeout"))
timed_out = _run(session, ds)
assert sql_error.failure_kind == "sql_error"
assert timed_out.failure_kind == "timeout" and "category" not in timed_out.details
stored = _stored(ds)
assert stored.circuit_failure_count == 0 and stored.circuit_state == "closed"
session.close()
def test_connection_lost_mid_query_counts_against_the_circuit(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session)
_install(
monkeypatch, QueryFailure("unreachable", category=ProbeCategory.UNREACHABLE)
)
result = _run(session, ds)
assert result.failure_kind == "unreachable"
assert _stored(ds).circuit_failure_count == 1
session.close()
def test_result_never_contains_driver_text(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session)
_install(monkeypatch, QueryFailure("sql_error"))
result = _run(session, ds)
blob = repr(result)
assert "synthetic_user" not in blob and "127.0.0.1" not in blob
session.close()
# --- driver classification with faked client libraries ------------------------------------
class _Boom(Exception):
pass
def test_mysql_connect_auth_error_maps_to_auth_failed(monkeypatch) -> None:
import pymysql
def connect(**_kwargs):
raise pymysql.err.OperationalError(1045, "Access denied for user 'x'@'h'")
monkeypatch.setattr(pymysql, "connect", connect)
target = _target("mysql")
with pytest.raises(ConnectFailure) as exc:
drivers.fetch_rows(target, "SELECT 1", None, timeout_ms=1000, limit=2, connect_timeout=1)
assert exc.value.category is ProbeCategory.AUTH_FAILED
assert "Access denied" not in str(exc.value)
def test_mysql_query_after_connect_is_read_only_and_maps_errors(monkeypatch) -> None:
import pymysql
executed: list[str] = []
class Cursor:
description = None
def __enter__(self):
return self
def __exit__(self, *_exc):
return False
def execute(self, sql, params=None):
executed.append(sql)
if sql.startswith("SELECT"):
raise pymysql.err.ProgrammingError(1064, "syntax near secret")
class Conn:
def cursor(self):
return Cursor()
def rollback(self):
pass
def close(self):
pass
monkeypatch.setattr(pymysql, "connect", lambda **_kwargs: Conn())
with pytest.raises(QueryFailure) as exc:
drivers.fetch_rows(
_target("mysql"), "SELECT x", None, timeout_ms=1000, limit=2, connect_timeout=1
)
assert exc.value.kind == "sql_error" and exc.value.category is None
assert executed[:2] == ["SET SESSION TRANSACTION READ ONLY", "START TRANSACTION READ ONLY"]
assert "secret" not in str(exc.value.details)
def test_mysql_lost_connection_is_connectivity_but_read_timeout_is_not(monkeypatch) -> None:
import pymysql
def make(error):
class Cursor:
description = None
def __enter__(self):
return self
def __exit__(self, *_exc):
return False
def execute(self, sql, params=None):
if sql.startswith("SELECT"):
raise error
class Conn:
def cursor(self):
return Cursor()
def rollback(self):
pass
def close(self):
pass
return Conn()
lost = pymysql.err.OperationalError(2006, "MySQL server has gone away")
monkeypatch.setattr(pymysql, "connect", lambda **_kwargs: make(lost))
with pytest.raises(QueryFailure) as exc:
drivers.fetch_rows(
_target("mysql"), "SELECT x", None, timeout_ms=1000, limit=2, connect_timeout=1
)
assert exc.value.kind == "unreachable" and exc.value.category is ProbeCategory.UNREACHABLE
slow = pymysql.err.OperationalError(2013, "Lost connection during query")
slow.__cause__ = TimeoutError("timed out")
monkeypatch.setattr(pymysql, "connect", lambda **_kwargs: make(slow))
with pytest.raises(QueryFailure) as exc:
drivers.fetch_rows(
_target("mysql"), "SELECT x", None, timeout_ms=1000, limit=2, connect_timeout=1
)
assert exc.value.kind == "timeout" and exc.value.category is None
def test_unsupported_engine_opens_nothing() -> None:
from watchman.datasources import UnsupportedDataSourceError
with pytest.raises(UnsupportedDataSourceError):
drivers.fetch_rows(
_target("oracle"), "SELECT 1", None, timeout_ms=1000, limit=2, connect_timeout=1
)
def _target(engine: str):
from watchman.datasources import ProbeTarget
return ProbeTarget(
engine=engine, host="127.0.0.1", port=1, database="d", username="u", password="p"
)
# --- live PostgreSQL ----------------------------------------------------------------------
@pytest.fixture()
def live():
env = merge_layered_env()
keys = ("HOST", "PORT", "USER", "PASSWORD", "DATABASE")
if any(not env.get(f"WATCHMAN_TEST_PG_{k}") for k in keys):
pytest.skip("WATCHMAN_TEST_PG_* env not configured")
values = {k: env[f"WATCHMAN_TEST_PG_{k}"] for k in keys}
from watchman.datasources import ProbeTarget, probe_datasource
precheck = probe_datasource(
ProbeTarget(
engine="postgresql",
host=values["HOST"],
port=int(values["PORT"]),
database=values["DATABASE"],
username=values["USER"],
password=values["PASSWORD"],
)
)
if precheck.category is not ProbeCategory.SUCCESS:
pytest.skip(f"live postgres not available ({precheck.category.value})")
return values
def _live_datasource(session, live, **overrides) -> str:
row = service.create_datasource(
session,
name=f"{NAME_PREFIX}{uuid.uuid4().hex[:10]}",
description=None,
kind="database",
engine="postgresql",
host=overrides.pop("host", live["HOST"]),
port=overrides.pop("port", int(live["PORT"])),
database_name=live["DATABASE"],
username=live["USER"],
password=overrides.pop("password", live["PASSWORD"]),
read_only_intent=True,
)
for key, value in overrides.items():
setattr(row, key, value)
session.commit()
return str(row.id)
def _live_run(session, ds, sql, *, params=None, schema=None, output=None, **kw):
return run_query(
session,
datasource_id=ds,
sql_template=sql,
param_schema=schema or [],
output_schema=output or [],
allowed_identifiers=kw.pop("allowed", []),
params=params or {},
timeout_ms=kw.pop("timeout_ms", 5000),
max_rows=kw.pop("max_rows", 100),
)
def test_live_binding_neutralizes_injection_and_escapes_percent(live) -> None:
session = _session()
ds = _live_datasource(session, live)
schema = [{"name": "v", "type": "string"}]
echoed = _live_run(
session,
ds,
"SELECT 'a%b' AS lit, :v AS v, 7::int AS n",
params={"v": INJECTION},
schema=schema,
output=[{"name": "v", "type": "string"}, {"name": "n", "type": "integer"}],
)
assert echoed.status == "success"
assert echoed.rows == [{"lit": "a%b", "v": INJECTION, "n": 7}]
matched = _live_run(
session,
ds,
"SELECT 1 AS one FROM (VALUES ('a'), ('b')) AS t(name) WHERE name = :v",
params={"v": "' OR '1'='1"},
schema=schema,
)
assert matched.status == "empty" # an injected tautology matched nothing
session.close()
def test_live_typed_params_and_whitelisted_identifier(live) -> None:
session = _session()
ds = _live_datasource(session, live)
schema = [
{"name": "n", "type": "integer"},
{"name": "f", "type": "number"},
{"name": "b", "type": "boolean"},
{"name": "t", "type": "datetime"},
]
result = _live_run(
session,
ds,
"SELECT :n AS n, :f AS f, :b AS b, :t AS t",
params={"n": 3, "f": 1.5, "b": True, "t": "2030-01-02T03:04:05+00:00"},
schema=schema,
output=[
{"name": "n", "type": "integer"},
{"name": "f", "type": "number"},
{"name": "b", "type": "boolean"},
{"name": "t", "type": "datetime"},
],
)
assert result.status == "success", result
assert result.rows[0]["n"] == 3 and result.rows[0]["b"] is True
# The server renders in its session time zone; the instant itself must be unchanged.
assert datetime.fromisoformat(result.rows[0]["t"]) == datetime(
2030, 1, 2, 3, 4, 5, tzinfo=timezone.utc
)
ident = _live_run(
session,
ds,
"SELECT count(*) AS c FROM {{pg_class}}",
allowed=["pg_class"],
output=[{"name": "c", "type": "integer"}],
)
assert ident.status == "success"
session.close()
def test_live_empty_illegal_type_and_sql_error_are_distinct(live) -> None:
session = _session()
ds = _live_datasource(session, live, circuit_failure_threshold=1)
empty = _live_run(session, ds, "SELECT 1 AS n WHERE false")
illegal = _live_run(
session, ds, "SELECT 'x' AS n", output=[{"name": "n", "type": "integer"}]
)
syntax = _live_run(session, ds, "SELEC 1")
assert (empty.status, illegal.status, syntax.status) == ("empty", "illegal_type", "failure")
assert syntax.failure_kind == "sql_error" and syntax.details["sqlstate"] == "42601"
assert "SELEC" not in repr(syntax)
stored = _stored(ds)
assert stored.circuit_failure_count == 0 and stored.circuit_state == "closed"
session.close()
def test_live_row_limit(live) -> None:
session = _session()
ds = _live_datasource(session, live)
sql = "SELECT g AS n FROM generate_series(1, 5) g"
output = [{"name": "n", "type": "integer"}]
exact = _live_run(session, ds, sql, output=output, max_rows=5)
over = _live_run(session, ds, sql, output=output, max_rows=4)
assert exact.status == "success" and len(exact.rows) == 5
assert over.failure_kind == "limit_exceeded" and over.rows == []
session.close()
def test_live_statement_timeout_is_not_a_connection_failure(live) -> None:
session = _session()
ds = _live_datasource(session, live, circuit_failure_threshold=1)
result = _live_run(session, ds, "SELECT pg_sleep(5)", timeout_ms=300)
assert result.failure_kind == "timeout"
stored = _stored(ds)
assert stored.circuit_failure_count == 0 and stored.circuit_state == "closed"
session.close()
def test_live_session_is_read_only(live) -> None:
session = _session()
ds = _live_datasource(session, live)
table = f"wm_ro_{uuid.uuid4().hex[:8]}"
created = _live_run(session, ds, f"CREATE TABLE {table} (i int)")
flag = _live_run(
session,
ds,
"SELECT current_setting('transaction_read_only') AS ro",
output=[{"name": "ro", "type": "string"}],
)
assert created.status == "failure"
assert flag.rows == [{"ro": "on"}]
exists = _live_run(
session, ds, f"SELECT to_regclass('{table}')::text AS r"
)
assert exists.rows == [{"r": None}]
session.close()
def test_live_wrong_password_records_auth_failure(live) -> None:
session = _session()
ds = _live_datasource(session, live, password="wrong-pw-not-a-credential")
result = _live_run(session, ds, "SELECT 1 AS n")
assert result.failure_kind == "auth_failed"
assert "wrong-pw" not in repr(result)
assert _stored(ds).circuit_failure_count == 1
session.close()
def test_live_unreachable_port_records_connection_failure(live) -> None:
session = _session()
ds = _live_datasource(session, live, host="127.0.0.1", port=1)
result = _live_run(session, ds, "SELECT 1 AS n")
assert result.failure_kind in ("unreachable", "timeout")
assert _stored(ds).circuit_failure_count == 1
session.close()
reset_engine()
@@ -0,0 +1,513 @@
"""Query definition/version constraints, RLS, and the version immutability helper.
The helper tests need no database; the persistence tests run against local Postgres like
test_datasource_rls.py and fail loudly if the migration was not applied.
"""
from __future__ import annotations
import uuid
import pytest
from sqlalchemy import create_engine, text
from sqlalchemy.exc import DBAPIError, IntegrityError
from sqlalchemy.orm import Session, sessionmaker
from _privileged_cleanup import purge_query_rows
from watchman.core.config import get_settings, reload_settings
from watchman.core.db import _ensure_after_begin_listener, reset_engine, set_tenant
from watchman.core.errors import ValidationError
from watchman.models import DataSource, QueryDefinition, QueryVersion
from watchman.models.query import VERSION_CONTENT_COLUMNS
from watchman.services.query_versions import (
assert_version_immutable,
forbid_version_content_mutation,
)
FAKE_CIPHERTEXT = "gAAAA-test-placeholder-ciphertext"
# --- helper tests (no database) -------------------------------------------------------
@pytest.mark.parametrize("column", sorted(VERSION_CONTENT_COLUMNS))
def test_helper_rejects_each_content_column(column: str) -> None:
with pytest.raises(ValidationError) as exc:
forbid_version_content_mutation({column: "x"})
assert exc.value.http_status == 400
assert exc.value.details["reason"] == "version_immutable"
assert exc.value.details["fields"] == [column]
@pytest.mark.parametrize("column", ["version_no", "published_by", "published_at", "tenant_id"])
def test_helper_rejects_identity_and_audit_columns(column: str) -> None:
with pytest.raises(ValidationError):
forbid_version_content_mutation({column: "x"})
def test_helper_allows_empty_and_unrelated_changes() -> None:
forbid_version_content_mutation({})
forbid_version_content_mutation({"unrelated": 1})
def test_assert_version_immutable_leaves_instance_untouched() -> None:
version = QueryVersion(version_no=1, sql_template="SELECT 1", max_rows=10)
with pytest.raises(ValidationError):
assert_version_immutable(version, {"sql_template": "DROP TABLE x"})
assert version.sql_template == "SELECT 1"
assert assert_version_immutable(version, {}) is version
# --- persistence tests ----------------------------------------------------------------
@pytest.fixture()
def q_factory():
reload_settings()
reset_engine()
_ensure_after_begin_listener()
settings = get_settings()
engine = create_engine(settings.database_url, pool_pre_ping=True)
factory = sessionmaker(bind=engine, autoflush=False, autocommit=False, expire_on_commit=False)
datasource_ids: list[tuple[str, uuid.UUID]] = [] # (tenant_id, datasource id)
yield factory, datasource_ids, settings
cleanup = factory()
try:
for tenant, ds_id in datasource_ids:
# Versions are append-only for the app role: superuser purge of versions and
# definitions, then the datasource they reference (RESTRICT) as the app role.
purge_query_rows(datasource_id=ds_id)
set_tenant(cleanup, tenant)
cleanup.execute(text("DELETE FROM data_sources WHERE id = :d"), {"d": ds_id})
cleanup.commit()
finally:
cleanup.close()
engine.dispose()
reset_engine()
def _datasource(session: Session, tenant: str, registry: list) -> uuid.UUID: # type: ignore[type-arg]
row = DataSource(
tenant_id=tenant,
name=f"q-ds-{uuid.uuid4().hex[:12]}",
kind="database",
engine="postgresql",
host="127.0.0.1",
port=5432,
database_name="synthetic",
username="synthetic_user",
secret_ciphertext=FAKE_CIPHERTEXT,
)
session.add(row)
session.commit()
registry.append((tenant, row.id))
return row.id
def _definition(tenant: str, datasource_id: uuid.UUID, **overrides) -> QueryDefinition: # type: ignore[no-untyped-def]
values = dict(
tenant_id=tenant,
name=f"q-{uuid.uuid4().hex[:12]}",
datasource_id=datasource_id,
draft_sql_template="SELECT 1",
)
values.update(overrides)
return QueryDefinition(**values)
def _version(tenant: str, definition_id: uuid.UUID, version_no: int = 1, **overrides) -> QueryVersion: # type: ignore[no-untyped-def]
values = dict(
tenant_id=tenant,
definition_id=definition_id,
version_no=version_no,
sql_template="SELECT 1",
param_schema=[],
output_schema=[],
allowed_identifiers=[],
timeout_ms=10000,
max_rows=100,
)
values.update(overrides)
return QueryVersion(**values)
def test_tables_force_rls_and_not_owned_by_app_role() -> None:
reload_settings()
engine = create_engine(get_settings().database_url, pool_pre_ping=True)
with engine.connect() as conn:
for table in ("query_definitions", "query_versions"):
owner = conn.execute(
text(
"SELECT tableowner FROM pg_tables "
"WHERE schemaname = 'public' AND tablename = :t"
),
{"t": table},
).scalar_one()
flags = conn.execute(
text(
"SELECT relrowsecurity, relforcerowsecurity FROM pg_class "
"WHERE relname = :t"
),
{"t": table},
).one()
assert owner != "watchman_app"
assert flags.relrowsecurity is True
assert flags.relforcerowsecurity is True
engine.dispose()
def test_insert_definition_and_version_with_defaults(q_factory) -> None: # type: ignore[no-untyped-def]
factory, registry, settings = q_factory
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
ds_id = _datasource(session, settings.tenant_id, registry)
definition = _definition(settings.tenant_id, ds_id)
session.add(definition)
session.commit()
session.add(_version(settings.tenant_id, definition.id))
session.commit()
stored = session.execute(
text(
"SELECT enabled, draft_param_schema, draft_output_schema, "
"draft_allowed_identifiers, draft_timeout_ms, draft_max_rows, "
"latest_published_version_no, current_version_no, "
"created_at IS NOT NULL AS has_created "
"FROM query_definitions WHERE id = :i"
),
{"i": definition.id},
).one()
assert stored.enabled is True
assert stored.draft_param_schema == []
assert stored.draft_output_schema == []
assert stored.draft_allowed_identifiers == []
assert stored.draft_timeout_ms == 10000
assert stored.draft_max_rows == 100
assert stored.latest_published_version_no is None
assert stored.current_version_no is None
assert stored.has_created is True
published = session.execute(
text(
"SELECT published_at IS NOT NULL AS ok, published_by "
"FROM query_versions WHERE definition_id = :i"
),
{"i": definition.id},
).one()
assert published.ok is True
assert published.published_by is None
finally:
session.close()
def test_other_tenant_cannot_see_definition_or_version(q_factory) -> None: # type: ignore[no-untyped-def]
factory, registry, settings = q_factory
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
ds_id = _datasource(session, settings.tenant_id, registry)
definition = _definition(settings.tenant_id, ds_id)
session.add(definition)
session.commit()
session.add(_version(settings.tenant_id, definition.id))
session.commit()
def_id = definition.id
finally:
session.close()
for tenant in ("other-tenant", None):
other: Session = factory()
try:
if tenant:
set_tenant(other, tenant)
assert other.execute(
text("SELECT count(*) FROM query_definitions WHERE id = :i"), {"i": def_id}
).scalar() == 0
assert other.execute(
text("SELECT count(*) FROM query_versions WHERE definition_id = :i"),
{"i": def_id},
).scalar() == 0
finally:
other.close()
same: Session = factory()
try:
set_tenant(same, settings.tenant_id)
assert same.execute(
text("SELECT count(*) FROM query_versions WHERE definition_id = :i"), {"i": def_id}
).scalar() == 1
finally:
same.close()
def test_write_for_foreign_tenant_is_rejected(q_factory) -> None: # type: ignore[no-untyped-def]
factory, registry, settings = q_factory
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
ds_id = _datasource(session, settings.tenant_id, registry)
session.add(_definition("other-tenant", ds_id))
with pytest.raises(DBAPIError):
session.commit()
session.rollback()
finally:
session.close()
def test_duplicate_definition_name_and_version_no_rejected(q_factory) -> None: # type: ignore[no-untyped-def]
factory, registry, settings = q_factory
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
ds_id = _datasource(session, settings.tenant_id, registry)
definition = _definition(settings.tenant_id, ds_id, name="dup-name")
session.add(definition)
session.commit()
session.add(_definition(settings.tenant_id, ds_id, name="dup-name"))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
session.add(_version(settings.tenant_id, definition.id, 1))
session.commit()
session.add(_version(settings.tenant_id, definition.id, 1))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
finally:
session.close()
@pytest.mark.parametrize(
"overrides",
[
{"draft_timeout_ms": 0},
{"draft_timeout_ms": 300001},
{"draft_max_rows": 0},
{"draft_max_rows": 10001},
{"latest_published_version_no": 0},
],
)
def test_definition_check_constraints(q_factory, overrides) -> None: # type: ignore[no-untyped-def]
factory, registry, settings = q_factory
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
ds_id = _datasource(session, settings.tenant_id, registry)
session.add(_definition(settings.tenant_id, ds_id, **overrides))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
finally:
session.close()
@pytest.mark.parametrize(
"overrides",
[{"timeout_ms": 0}, {"timeout_ms": 300001}, {"max_rows": 0}, {"max_rows": 10001}],
)
def test_version_numeric_checks_and_version_no(q_factory, overrides) -> None: # type: ignore[no-untyped-def]
factory, registry, settings = q_factory
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
ds_id = _datasource(session, settings.tenant_id, registry)
definition = _definition(settings.tenant_id, ds_id)
session.add(definition)
session.commit()
session.add(_version(settings.tenant_id, definition.id, **overrides))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
session.add(_version(settings.tenant_id, definition.id, version_no=0))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
finally:
session.close()
def test_datasource_delete_restricted_while_definition_exists(q_factory) -> None: # type: ignore[no-untyped-def]
factory, registry, settings = q_factory
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
ds_id = _datasource(session, settings.tenant_id, registry)
session.add(_definition(settings.tenant_id, ds_id))
session.commit()
with pytest.raises(IntegrityError):
session.execute(text("DELETE FROM data_sources WHERE id = :d"), {"d": ds_id})
session.rollback()
finally:
session.close()
def test_helper_blocks_update_of_persisted_version(q_factory) -> None: # type: ignore[no-untyped-def]
"""The helper rejects the change, so the stored row keeps its published content."""
factory, registry, settings = q_factory
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
ds_id = _datasource(session, settings.tenant_id, registry)
definition = _definition(settings.tenant_id, ds_id)
session.add(definition)
session.commit()
version = _version(settings.tenant_id, definition.id, sql_template="SELECT 42")
session.add(version)
session.commit()
with pytest.raises(ValidationError):
assert_version_immutable(version, {"sql_template": "SELECT 43", "max_rows": 5})
stored = session.execute(
text("SELECT sql_template, max_rows FROM query_versions WHERE id = :i"),
{"i": version.id},
).one()
assert stored.sql_template == "SELECT 42"
assert stored.max_rows == 100
finally:
session.close()
# --- database-enforced immutability (migration 0007) ---------------------------------------
def _published_version(session: Session, settings, registry) -> tuple[uuid.UUID, uuid.UUID]: # type: ignore[no-untyped-def]
set_tenant(session, settings.tenant_id)
ds_id = _datasource(session, settings.tenant_id, registry)
definition = _definition(settings.tenant_id, ds_id)
session.add(definition)
session.commit()
version = _version(settings.tenant_id, definition.id, sql_template="SELECT 42")
session.add(version)
session.commit()
return definition.id, version.id
def _stored_sql(factory, settings, version_id: uuid.UUID) -> str: # type: ignore[no-untyped-def]
check: Session = factory()
try:
set_tenant(check, settings.tenant_id)
return check.execute(
text("SELECT sql_template FROM query_versions WHERE id = :i"), {"i": version_id}
).scalar_one()
finally:
check.close()
def test_app_role_privileges_on_query_versions_are_append_only() -> None:
reload_settings()
engine = create_engine(get_settings().database_url, pool_pre_ping=True)
with engine.connect() as conn:
granted = {
privilege: conn.execute(
text("SELECT has_table_privilege('watchman_app', 'query_versions', :p)"),
{"p": privilege},
).scalar_one()
for privilege in ("SELECT", "INSERT", "UPDATE", "DELETE", "TRUNCATE")
}
engine.dispose()
assert granted == {
"SELECT": True,
"INSERT": True,
"UPDATE": False,
"DELETE": False,
"TRUNCATE": False,
}
def test_insert_new_version_still_works_under_app_role(q_factory) -> None: # type: ignore[no-untyped-def]
factory, registry, settings = q_factory
session: Session = factory()
try:
definition_id, _ = _published_version(session, settings, registry)
session.add(_version(settings.tenant_id, definition_id, version_no=2, sql_template="SELECT 2"))
session.commit()
count = session.execute(
text("SELECT count(*) FROM query_versions WHERE definition_id = :d"),
{"d": definition_id},
).scalar_one()
assert count == 2
finally:
session.close()
def test_app_role_core_update_and_delete_of_version_fail_in_database(q_factory) -> None: # type: ignore[no-untyped-def]
factory, registry, settings = q_factory
session: Session = factory()
try:
_, version_id = _published_version(session, settings, registry)
with pytest.raises(DBAPIError) as update_exc:
session.execute(
text("UPDATE query_versions SET sql_template = 'DROP TABLE x' WHERE id = :i"),
{"i": version_id},
)
assert getattr(update_exc.value.orig, "sqlstate", None) == "42501" # insufficient_privilege
session.rollback()
with pytest.raises(DBAPIError) as delete_exc:
session.execute(text("DELETE FROM query_versions WHERE id = :i"), {"i": version_id})
assert getattr(delete_exc.value.orig, "sqlstate", None) == "42501"
session.rollback()
assert _stored_sql(factory, settings, version_id) == "SELECT 42"
finally:
session.close()
def test_app_role_orm_update_and_delete_of_version_fail_in_database(q_factory) -> None: # type: ignore[no-untyped-def]
factory, registry, settings = q_factory
session: Session = factory()
try:
_, version_id = _published_version(session, settings, registry)
version = session.get(QueryVersion, version_id)
assert version is not None
version.sql_template = "DROP TABLE x"
with pytest.raises(DBAPIError):
session.commit()
session.rollback()
version = session.get(QueryVersion, version_id)
assert version is not None
session.delete(version)
with pytest.raises(DBAPIError):
session.commit()
session.rollback()
assert _stored_sql(factory, settings, version_id) == "SELECT 42"
finally:
session.close()
def test_trigger_rejects_update_delete_even_for_table_owner(q_factory) -> None: # type: ignore[no-untyped-def]
"""The owner (migrator) holds every privilege, so only the trigger can stop it.
The statement-level trigger fires even though forced RLS shows the owner zero rows.
"""
factory, registry, settings = q_factory
session: Session = factory()
try:
_, version_id = _published_version(session, settings, registry)
finally:
session.close()
owner_engine = create_engine(settings.database_migrator_url, pool_pre_ping=True)
try:
for statement in (
"UPDATE query_versions SET sql_template = 'x' WHERE id = :i",
"DELETE FROM query_versions WHERE id = :i",
"UPDATE query_versions SET max_rows = max_rows",
"DELETE FROM query_versions",
"TRUNCATE query_versions",
):
with owner_engine.connect() as conn:
with pytest.raises(DBAPIError) as exc:
conn.execute(text(statement), {"i": version_id} if ":i" in statement else {})
assert getattr(exc.value.orig, "sqlstate", None) == "23001" # restrict_violation
assert "append-only" in str(exc.value.orig)
conn.rollback()
finally:
owner_engine.dispose()
assert _stored_sql(factory, settings, version_id) == "SELECT 42"
+39 -2
View File
@@ -197,7 +197,39 @@ async function mockDatasources(page: Page, rows: Row[] = seedRows()): Promise<Mo
}
if (parts.length === 1) {
if (method === "GET") {
return json(200, ok({ items: mock.rows }));
const name = (url.searchParams.get("name") || "").trim().toLowerCase();
const engine = url.searchParams.get("engine") || "";
const enabledParam = url.searchParams.get("enabled");
const page = Number(url.searchParams.get("page") || "1");
const pageSize = Number(url.searchParams.get("page_size") || "20");
const sortBy = url.searchParams.get("sort_by") || "created_at";
const sortOrder = url.searchParams.get("sort_order") || "asc";
let rows = [...mock.rows];
if (name) {
rows = rows.filter((item) => item.name.toLowerCase().includes(name));
}
if (engine) {
rows = rows.filter((item) => item.engine === engine);
}
if (enabledParam === "true") {
rows = rows.filter((item) => item.enabled);
}
if (enabledParam === "false") {
rows = rows.filter((item) => !item.enabled);
}
const dir = sortOrder === "asc" ? 1 : -1;
rows.sort((a, b) => {
const av = (a as Record<string, unknown>)[sortBy];
const bv = (b as Record<string, unknown>)[sortBy];
if (av === bv) return 0;
if (av == null) return 1;
if (bv == null) return -1;
return av < bv ? -dir : dir;
});
const total = rows.length;
const start = Math.max(0, (page - 1) * pageSize);
const items = rows.slice(start, start + pageSize);
return json(200, ok({ items, total, page, page_size: pageSize }));
}
const created = row({ id: "55555555-5555-4555-8555-555555555555", name: "x" });
Object.assign(created, body, { secret_configured: true });
@@ -262,11 +294,13 @@ test.describe("datasources console", () => {
await expect(page.getByTestId("datasource-table")).toBeVisible();
const crumb = page.getByTestId("breadcrumb");
await expect(crumb).toContainText("Watchman");
await expect(crumb).toContainText("预警平台");
await expect(crumb).toContainText("数据源");
await expect(crumb).not.toContainText("新建");
await expect(crumb).not.toContainText("详情");
await expect(page.getByTestId("nav-datasources")).toBeVisible();
await expect(page.getByTestId("side-logo")).toBeVisible();
await expect(page.getByTestId("side-user").getByTestId("shell-welcome")).toBeVisible();
for (const header of ["名称", "引擎", "主机", "端口", "库名", "用户名", "状态", "最近测试", "操作"]) {
await expect(page.locator(".el-table__header").getByText(header, { exact: true })).toBeVisible();
@@ -275,6 +309,9 @@ test.describe("datasources console", () => {
await expect(page.getByTestId("datasource-table")).toContainText("SQL Server");
await expect(page.getByTestId("datasource-table")).toContainText("2026-11-17");
await expect(page.getByTestId("datasource-table")).toContainText("尚未测试");
await expect(page.getByTestId("datasource-pagination")).toBeVisible();
await expect(page.getByTestId("datasource-filter-search")).toBeVisible();
await expect(page.getByTestId("datasource-filter-reset")).toBeVisible();
// 新建 sits above the table, right aligned.
const create = await page.getByTestId("datasource-create").boundingBox();
+967
View File
@@ -0,0 +1,967 @@
import { expect, test, type Page, type Route } from "@playwright/test";
import path from "node:path";
import { fileURLToPath } from "node:url";
const evidenceDir = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
"../../../../docs/evidence/M04/ui",
);
// Synthetic data only. The API is mocked; no source database or secret is involved.
const SERVER_TEXT = "FATAL: driver said something private";
type Draft = {
sql_template: string;
param_schema: Record<string, unknown>[];
output_schema: Record<string, unknown>[];
allowed_identifiers: string[];
timeout_ms: number;
max_rows: number;
};
type Def = {
id: string;
name: string;
description: string | null;
datasource_id: string;
enabled: boolean;
current_version_no: number | null;
latest_version_no: number | null;
latest_published_version_no: number | null;
created_at: string;
updated_at: string;
current: Draft;
};
type Ver = Draft & {
id: string;
definition_id: string;
version_no: number;
published_at: string;
published_by: string;
};
const DS_ONE = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
const DS_TWO = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
const DS_OFF = "cccccccc-cccc-4ccc-8ccc-cccccccccccc";
const Q_ONE = "11111111-1111-4111-8111-111111111111";
const Q_TWO = "22222222-2222-4222-8222-222222222222";
const Q_OFF = "33333333-3333-4333-8333-333333333333";
const Q_NEW = "55555555-5555-4555-8555-555555555555";
function datasourceRows() {
const base = {
description: null,
kind: "database",
engine: "postgresql",
host: "db.example.test",
port: 5432,
database_name: "process_demo",
username: "readonly_demo",
secret_configured: true,
read_only_intent: true,
circuit_state: "closed",
circuit_opened_at: null,
circuit_open_until: null,
circuit_failure_window_seconds: 300,
circuit_failure_threshold: 3,
circuit_open_cooldown_seconds: 600,
last_test_category: null,
last_test_at: null,
last_test_message: null,
created_at: "2026-11-17T01:00:00+00:00",
updated_at: "2026-11-17T01:00:00+00:00",
};
return [
{ ...base, id: DS_ONE, name: "产线工艺库", enabled: true },
{ ...base, id: DS_TWO, name: "设备台账库", enabled: true },
{ ...base, id: DS_OFF, name: "历史归档库", enabled: false },
];
}
const SQL_ONE =
"SELECT lot_no, temperature, phone\nFROM process_readings\nWHERE line_code = :line_code";
function draftOne(): Draft {
return {
sql_template: SQL_ONE,
param_schema: [
{ name: "line_code", type: "string", required: true },
{ name: "min_temp", type: "number", required: false, default: 0 },
],
output_schema: [
{ name: "lot_no", type: "string" },
{ name: "temperature", type: "number" },
{ name: "phone", type: "string" },
],
allowed_identifiers: ["process_readings"],
timeout_ms: 5000,
max_rows: 200,
};
}
function def(overrides: Partial<Def> & Pick<Def, "id" | "name">): Def {
return {
description: "示例(虚构)",
datasource_id: DS_ONE,
enabled: true,
current_version_no: 1,
latest_version_no: 1,
latest_published_version_no: 1,
created_at: "2026-11-17T01:00:00+00:00",
updated_at: "2026-11-18T01:40:00+00:00",
current: draftOne(),
...overrides,
};
}
function seedDefs(): Def[] {
return [
def({ id: Q_ONE, name: "产线温度采样", current_version_no: 1, latest_version_no: 1 }),
def({
id: Q_TWO,
name: "设备停机记录",
datasource_id: DS_TWO,
current: {
...draftOne(),
sql_template: "SELECT 1",
param_schema: [],
output_schema: [],
allowed_identifiers: [],
},
}),
def({ id: Q_OFF, name: "质检不良统计", enabled: false }),
];
}
function seedVersions(): Ver[] {
return [
{
...draftOne(),
id: "v-1",
definition_id: Q_ONE,
version_no: 1,
published_at: "2026-11-18T01:40:00+00:00",
published_by: "admin.demo",
},
];
}
function ok(data: unknown): string {
return JSON.stringify({ success: true, data, request_id: "pw-q" });
}
function fail(code: number, message: string, details: Record<string, unknown> = {}): string {
return JSON.stringify({
success: false,
error: { code, message, details, retryable: false },
request_id: "pw-q",
});
}
type Outcome = { status: number; body: string; delayMs: number };
type Mock = {
defs: Def[];
versions: Ver[];
requests: { method: string; pathname: string; body: unknown }[];
preview: Outcome;
};
const SUCCESS_BODY = ok({
id: Q_ONE,
version_no: 1,
source: "current",
status: "success",
message: "query succeeded",
columns: ["lot_no", "temperature", "phone"],
rows: [
{ lot_no: "LOT-1001", temperature: 71.2, phone: "***" },
{ lot_no: "LOT-1002", temperature: 72, phone: null },
],
row_count: 2,
masked_columns: ["phone"],
});
function previewBody(data: Record<string, unknown>): string {
return ok({ id: Q_ONE, version_no: 1, source: "current", message: "m", ...data });
}
async function signIn(page: Page, roles: string[]): Promise<void> {
await page.route("**/auth/me", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: ok({ subject: "user-1", display_name: "Worker", roles }),
});
});
await page.route("**/health", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: ok({ status: "ok", app: "watchman", version: "0.1.0" }),
});
});
}
function summary(row: Def): Omit<Def, "current"> {
const { current: _current, ...rest } = row;
return rest;
}
function versionSummary(row: Ver) {
return {
id: row.id,
definition_id: row.definition_id,
version_no: row.version_no,
published_at: row.published_at,
published_by: row.published_by,
};
}
/** Mocks /queries and the datasource list. Page source files under /src/... never match. */
async function mockApi(page: Page, defs: Def[] = seedDefs(), versions: Ver[] = seedVersions()): Promise<Mock> {
const mock: Mock = {
defs,
versions,
requests: [],
preview: { status: 200, delayMs: 0, body: SUCCESS_BODY },
};
const sources = datasourceRows();
const matcher = (url: URL) =>
/^\/datasources$/.test(url.pathname) ||
/^\/queries(\/[^/]+(\/(enable|disable|preview|references|versions(\/\d+(\/(preview|activate))?)?))?)?$/.test(
url.pathname,
);
await page.route(matcher, async (route: Route) => {
const request = route.request();
const url = new URL(request.url());
const method = request.method();
let body: unknown = null;
if (method === "POST" || method === "PATCH") {
body = request.postData() ? request.postDataJSON() : null;
}
mock.requests.push({ method, pathname: url.pathname, body });
const json = (status: number, text: string) =>
route.fulfill({ status, contentType: "application/json", body: text });
const parts = url.pathname.split("/").filter(Boolean);
if (parts[0] === "datasources") {
const page = Number(url.searchParams.get("page") || "1");
const pageSize = Number(url.searchParams.get("page_size") || "20");
return json(
200,
ok({ items: sources, total: sources.length, page, page_size: pageSize }),
);
}
if (parts.length === 1) {
if (method === "GET") {
const name = (url.searchParams.get("name") || "").trim().toLowerCase();
const datasourceId = url.searchParams.get("datasource_id") || "";
const enabledParam = url.searchParams.get("enabled");
const page = Number(url.searchParams.get("page") || "1");
const pageSize = Number(url.searchParams.get("page_size") || "20");
const sortBy = url.searchParams.get("sort_by") || "updated_at";
const sortOrder = url.searchParams.get("sort_order") || "desc";
let rows = mock.defs.map(summary);
if (name) {
rows = rows.filter((item) => item.name.toLowerCase().includes(name));
}
if (datasourceId) {
rows = rows.filter((item) => item.datasource_id === datasourceId);
}
if (enabledParam === "true") {
rows = rows.filter((item) => item.enabled);
}
if (enabledParam === "false") {
rows = rows.filter((item) => !item.enabled);
}
const dir = sortOrder === "asc" ? 1 : -1;
rows = [...rows].sort((a, b) => {
const av = (a as Record<string, unknown>)[sortBy === "datasource_name" ? "datasource_id" : sortBy];
const bv = (b as Record<string, unknown>)[sortBy === "datasource_name" ? "datasource_id" : sortBy];
if (av === bv) return 0;
if (av == null) return 1;
if (bv == null) return -1;
return av < bv ? -dir : dir;
});
const total = rows.length;
const start = Math.max(0, (page - 1) * pageSize);
const items = rows.slice(start, start + pageSize);
return json(200, ok({ items, total, page, page_size: pageSize }));
}
const payload = body as Record<string, unknown>;
if (mock.defs.some((item) => item.name === payload.name)) {
return json(409, fail(40000, "Query name already exists", { reason: "duplicate_name" }));
}
const content = {
sql_template: String(payload.sql_template),
param_schema: payload.param_schema as Record<string, unknown>[],
output_schema: payload.output_schema as Record<string, unknown>[],
allowed_identifiers: payload.allowed_identifiers as string[],
timeout_ms: Number(payload.timeout_ms),
max_rows: Number(payload.max_rows),
};
const created = def({
id: Q_NEW,
name: String(payload.name),
description: (payload.description as string | null) ?? null,
datasource_id: String(payload.datasource_id),
current: content,
current_version_no: 1,
latest_version_no: 1,
latest_published_version_no: 1,
});
mock.defs.push(created);
mock.versions.push({
...content,
id: `v-${Q_NEW}-1`,
definition_id: Q_NEW,
version_no: 1,
published_at: "2026-11-18T02:00:00+00:00",
published_by: "admin.demo",
});
return json(200, ok({ ...summary(created), current: created.current }));
}
const found = mock.defs.find((item) => item.id === parts[1]);
if (!found) {
return json(404, fail(40000, "Query not found", { reason: "not_found" }));
}
const full = () => ok({ ...summary(found), current: found.current });
const action = parts[2];
if (!action) {
if (method === "GET") {
return json(200, full());
}
const patch = body as Record<string, unknown>;
if (mock.defs.some((item) => item.name === patch.name && item.id !== found.id)) {
return json(409, fail(40000, "Query name already exists", { reason: "duplicate_name" }));
}
if (
"sql_template" in patch ||
"param_schema" in patch ||
"output_schema" in patch ||
"timeout_ms" in patch ||
"max_rows" in patch
) {
return json(400, fail(40000, "use save version", { reason: "use_save_version" }));
}
found.name = String(patch.name ?? found.name);
found.description = (patch.description as string | null) ?? null;
found.datasource_id = String(patch.datasource_id ?? found.datasource_id);
return json(200, full());
}
if (action === "enable" || action === "disable") {
found.enabled = action === "enable";
return json(200, full());
}
if (action === "references") {
return json(200, ok({ id: found.id, items: [] }));
}
const own = mock.versions
.filter((item) => item.definition_id === found.id)
.sort((a, b) => b.version_no - a.version_no);
if (action === "versions" && parts.length === 3) {
if (method === "POST") {
const payload = body as Record<string, unknown>;
const next = (found.latest_version_no ?? 0) + 1;
const content = {
sql_template: String(payload.sql_template),
param_schema: (payload.param_schema as Record<string, unknown>[]) ?? [],
output_schema: (payload.output_schema as Record<string, unknown>[]) ?? [],
allowed_identifiers: (payload.allowed_identifiers as string[]) ?? [],
timeout_ms: Number(payload.timeout_ms ?? 10000),
max_rows: Number(payload.max_rows ?? 100),
};
const version: Ver = {
...content,
id: `v-${found.id}-${next}`,
definition_id: found.id,
version_no: next,
published_at: "2026-11-18T02:00:00+00:00",
published_by: "admin.demo",
};
mock.versions.push(version);
found.current = content;
found.current_version_no = next;
found.latest_version_no = next;
found.latest_published_version_no = next;
return json(200, ok(version));
}
return json(200, ok({ id: found.id, items: own.map(versionSummary) }));
}
if (action === "versions" && parts.length === 4) {
const frozen = own.find((item) => item.version_no === Number(parts[3]));
return frozen ? json(200, ok(frozen)) : json(404, fail(40000, "Query version not found", { reason: "not_found" }));
}
if (action === "versions" && parts[4] === "activate") {
const no = Number(parts[3]);
const frozen = own.find((item) => item.version_no === no);
if (!frozen) {
return json(404, fail(40000, "Query version not found", { reason: "not_found" }));
}
found.current_version_no = no;
found.current = {
sql_template: frozen.sql_template,
param_schema: frozen.param_schema,
output_schema: frozen.output_schema,
allowed_identifiers: frozen.allowed_identifiers,
timeout_ms: frozen.timeout_ms,
max_rows: frozen.max_rows,
};
return json(200, full());
}
if (action === "preview" || parts[4] === "preview") {
if (!found.enabled) {
return json(409, fail(40000, "Query is disabled", { reason: "disabled" }));
}
await new Promise((resolve) => setTimeout(resolve, mock.preview.delayMs));
return json(mock.preview.status, mock.preview.body);
}
return json(404, fail(40000, "Not found", { reason: "not_found" }));
});
return mock;
}
async function pickDatasource(page: Page, name: string): Promise<void> {
await page.getByTestId("field-datasource").locator(".el-select__wrapper").click();
await page.getByRole("option", { name }).click();
}
async function confirmDialog(page: Page): Promise<void> {
await page.locator(".el-message-box__btns .el-button--primary").click();
}
async function fillCreateForm(page: Page, name: string): Promise<void> {
await page.getByTestId("field-name").locator("input").fill(name);
await pickDatasource(page, "设备台账库");
await page.getByTestId("field-sql").locator("textarea").fill("SELECT lot_no FROM {{process_readings}} WHERE line_code = :line_code");
await page.getByTestId("param-add").click();
await page.getByTestId("param-name").fill("line_code");
await page.getByTestId("output-add").click();
await page.getByTestId("output-name").fill("lot_no");
await page.getByTestId("identifier-input").fill("process_readings");
await page.getByTestId("identifier-add").click();
}
test.describe("queries console", () => {
test("a viewer and an operator see 无法进入查询 and no request is made", async ({ page }) => {
await signIn(page, ["watchman-viewer"]);
const mock = await mockApi(page);
await page.goto("/#/queries");
await expect(page.getByTestId("query-denied")).toContainText("无法进入查询");
await expect(page.getByTestId("breadcrumb")).toContainText("查询");
await expect(page.getByTestId("query-table")).toHaveCount(0);
await expect(page.getByTestId("query-create")).toHaveCount(0);
await page.screenshot({ path: path.join(evidenceDir, "query-denied-viewer.png"), fullPage: true });
// Deep links are gated too, and the breadcrumb stays at the list level.
await page.goto(`/#/queries/${Q_ONE}`);
await expect(page.getByTestId("query-denied")).toBeVisible();
await page.goto("/#/queries/new");
await expect(page.getByTestId("query-denied")).toBeVisible();
await expect(page.getByTestId("breadcrumb")).not.toContainText("新建");
await page.goto(`/#/queries/${Q_ONE}/versions/1`);
await expect(page.getByTestId("query-denied")).toBeVisible();
await expect(page.getByTestId("breadcrumb")).not.toContainText("版本");
expect(mock.requests).toHaveLength(0);
await page.unroute("**/auth/me");
await signIn(page, ["watchman-operator"]);
await page.goto("/#/queries");
await page.reload();
await expect(page.getByTestId("query-denied")).toBeVisible();
expect(mock.requests).toHaveLength(0);
});
test("empty list shows the empty state with 新建 above it", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
await mockApi(page, [], []);
await page.goto("/#/queries");
await expect(page.getByTestId("query-empty")).toContainText("还没有查询");
await expect(page.getByTestId("query-create")).toBeVisible();
const create = (await page.getByTestId("query-create").boundingBox())!;
const empty = (await page.getByTestId("query-empty").boundingBox())!;
expect(create.y + create.height).toBeLessThanOrEqual(empty.y);
await page.screenshot({ path: path.join(evidenceDir, "query-empty.png"), fullPage: true });
});
test("admin list: breadcrumb, 新建 above the table, columns, disabled row", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
await mockApi(page);
await page.goto("/#/queries");
await expect(page.getByTestId("query-table")).toBeVisible();
await expect(page.getByTestId("nav-queries")).toBeVisible();
const crumb = page.getByTestId("breadcrumb");
await expect(crumb).toContainText("预警平台");
await expect(crumb).toContainText("查询");
await expect(crumb).not.toContainText("新建");
await expect(crumb).not.toContainText("详情");
// No page title repeated under the breadcrumb.
await expect(page.getByRole("heading")).toHaveCount(0);
await expect(page.getByTestId("side-logo")).toBeVisible();
await expect(page.getByTestId("side-user").getByTestId("shell-welcome")).toBeVisible();
await expect(page.getByTestId("side-user").getByTestId("logout")).toBeVisible();
for (const header of ["名称", "数据源", "状态", "当前版本", "更新时间", "操作"]) {
await expect(page.locator(".el-table__header").getByText(header, { exact: true })).toBeVisible();
}
const table = page.getByTestId("query-table");
await expect(table).toContainText("产线温度采样");
await expect(table).toContainText("产线工艺库");
await expect(table).toContainText("v1");
await expect(table).toContainText("2026-11-18");
await expect(page.getByTestId(`query-row-${Q_ONE}`).getByTestId("row-switch-version")).toBeVisible();
await expect(page.getByTestId("query-pagination")).toBeVisible();
const create = (await page.getByTestId("query-create").boundingBox())!;
const box = (await table.boundingBox())!;
expect(create.y + create.height).toBeLessThanOrEqual(box.y);
expect(create.x + create.width).toBeGreaterThan(box.x + box.width - 40);
await expect(page.getByTestId("query-footer")).toHaveCount(0);
await expect(page.getByTestId("query-list-toolbar")).toBeVisible();
await expect(page.getByTestId("query-filter-name")).toBeVisible();
await expect(page.getByTestId("query-filter-datasource")).toBeVisible();
await expect(page.getByTestId("query-filter-status")).toBeVisible();
await expect(page.getByTestId("query-filter-search")).toBeVisible();
await expect(page.getByTestId("query-filter-reset")).toBeVisible();
// Draft filters do not apply until 查询 is clicked.
await page.getByTestId("query-filter-name").getByRole("textbox").fill("温度");
await expect(table).toContainText("质检不良统计");
await page.getByTestId("query-filter-search").click();
await expect(table).toContainText("产线温度采样");
await expect(table).not.toContainText("质检不良统计");
await page.getByTestId("query-filter-reset").click();
await expect(table).toContainText("质检不良统计");
// Disabled row: visible, 预览 disabled with a title, 打开 still works.
const off = page.getByTestId(`query-row-${Q_OFF}`);
await expect(off).toBeVisible();
await expect(off.getByTestId("row-preview")).toBeDisabled();
await expect(off.getByTestId("row-preview")).toHaveAttribute("title", "已停用,不能预览");
await expect(off.getByTestId("row-open")).toBeEnabled();
const live = page.getByTestId(`query-row-${Q_ONE}`);
await expect(live.getByTestId("row-preview")).toBeEnabled();
await expect(page.locator("body")).not.toContainText("正式版本进行删除");
await expect(page.locator("body")).not.toContainText("原型");
await page.screenshot({ path: path.join(evidenceDir, "query-list.png"), fullPage: true });
});
test("create: footer, validation, then save creates v1 and opens the detail", async ({
page,
}) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockApi(page);
await page.goto("/#/queries");
await page.getByTestId("query-create").click();
const crumb = page.getByTestId("breadcrumb");
await expect(crumb).toContainText("新建");
await expect(crumb).not.toContainText("详情");
await expect(page.getByTestId("basic-sub")).toContainText("新建");
await expect(page.getByTestId("versions-create-note")).toBeVisible();
// Create footer: 返回列表, 保存 live; 试跑预览 disabled until saved. No publish.
await expect(page.getByTestId("footer-back")).toHaveText("返回列表");
await expect(page.getByTestId("footer-save")).toHaveText("保存");
await expect(page.getByTestId("footer-publish")).toHaveCount(0);
await expect(page.getByTestId("footer-preview")).toBeDisabled();
await expect(page.getByTestId("footer-enable")).toHaveCount(0);
await expect(page.getByTestId("footer-disable")).toHaveCount(0);
await expect(page.getByTestId("preview-need-save")).toBeVisible();
// SQL textarea is monospace.
const font = await page
.getByTestId("field-sql")
.locator("textarea")
.evaluate((el) => getComputedStyle(el).fontFamily);
expect(font.toLowerCase()).toMatch(/mono|consolas/);
// A blank form does not submit.
await page.getByTestId("footer-save").click();
for (const field of ["name", "datasource", "sql"]) {
await expect(page.getByTestId(`field-${field}`).locator(".el-form-item__error")).toBeVisible();
}
expect(mock.requests.filter((item) => item.method === "POST")).toHaveLength(0);
// Undeclared SQL parameter is flagged live; an invalid parameter name and a limit are refused.
await page.getByTestId("field-sql").locator("textarea").fill("SELECT 1 WHERE a = :line_code AND b = :since");
await expect(page.getByTestId("chip-undeclared")).toHaveCount(2);
await expect(page.getByTestId("chip-undeclared").filter({ hasText: ":since 未声明" })).toBeVisible();
await page.getByTestId("param-add").click();
await page.getByTestId("param-name").fill("1bad");
await page.getByTestId("footer-save").click();
await expect(page.getByTestId("field-params").locator(".el-form-item__error")).toContainText("参数名不合法");
await page.getByTestId("param-name").fill("line_code");
await page.getByTestId("field-timeout").locator("input").fill("300001");
await page.getByTestId("field-timeout").locator("input").press("Tab");
await expect(page.getByTestId("field-timeout").locator(".el-form-item__error")).toContainText("1–300000");
await page.getByTestId("field-max-rows").locator("input").fill("0");
await page.getByTestId("field-max-rows").locator("input").press("Tab");
await expect(page.getByTestId("field-max-rows").locator(".el-form-item__error")).toContainText("1–10000");
await page.screenshot({ path: path.join(evidenceDir, "query-create-validation.png"), fullPage: true });
expect(mock.requests.filter((item) => item.method === "POST")).toHaveLength(0);
// Happy path.
await page.reload();
await fillCreateForm(page, "新建演示查询");
await page.getByTestId("field-timeout").locator("input").fill("5000");
await page.getByTestId("field-max-rows").locator("input").fill("50");
await page.screenshot({ path: path.join(evidenceDir, "query-create.png"), fullPage: true });
await page.getByTestId("footer-save").click();
// Saved: the detail page opens with v1 current and no publish button.
await expect(page.getByTestId("breadcrumb")).toContainText("详情");
await expect(page.getByTestId("field-name").locator("input")).toHaveValue("新建演示查询");
await expect(page.getByTestId("footer-publish")).toHaveCount(0);
await expect(page.getByTestId("footer-disable")).toBeVisible();
await expect(page.getByTestId("footer-preview")).toBeEnabled();
await expect(page.getByTestId("basic-sub")).toContainText("当前生效 v1");
const post = mock.requests.find((item) => item.method === "POST" && item.pathname === "/queries");
expect(post).toBeTruthy();
const body = post!.body as Record<string, unknown>;
expect(Object.keys(body).sort()).toEqual([
"allowed_identifiers",
"datasource_id",
"description",
"max_rows",
"name",
"output_schema",
"param_schema",
"sql_template",
"timeout_ms",
]);
expect(body.name).toBe("新建演示查询");
expect(body.datasource_id).toBe(DS_TWO);
expect(body.param_schema).toEqual([{ name: "line_code", type: "string", required: true }]);
expect(body.output_schema).toEqual([{ name: "lot_no", type: "string" }]);
expect(body.allowed_identifiers).toEqual(["process_readings"]);
expect(body.timeout_ms).toBe(5000);
expect(body.max_rows).toBe(50);
});
test("a disabled datasource cannot be picked", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
await mockApi(page);
await page.goto("/#/queries/new");
await page.getByTestId("field-datasource").locator(".el-select__wrapper").click();
await expect(page.getByRole("option", { name: /历史归档库/ })).toHaveClass(/is-disabled/);
await expect(page.getByRole("option", { name: /产线工艺库/ })).not.toHaveClass(/is-disabled/);
});
test("duplicate name shows the API reason on the form", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
await mockApi(page);
await page.goto("/#/queries/new");
await fillCreateForm(page, "产线温度采样");
await page.getByTestId("footer-save").click();
await expect(page.getByTestId("query-save-error")).toContainText("名称已存在");
await expect(page.getByTestId("query-save-error")).not.toContainText("Query name already exists");
});
test("detail: footer outside the scroll area, centered, in order; sections present", async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 520 });
await signIn(page, ["watchman-admin"]);
await mockApi(page);
await page.goto("/#/queries");
await page.getByTestId(`query-row-${Q_ONE}`).getByTestId("row-open").click();
const crumb = page.getByTestId("breadcrumb");
await expect(crumb).toContainText("详情");
await expect(crumb).not.toContainText("新建");
await expect(page.getByRole("heading", { level: 1 })).toHaveCount(0);
await expect(page.getByTestId("field-name").locator("input")).toHaveValue("产线温度采样");
await expect(page.getByTestId("basic-sub")).toContainText("当前生效 v1");
await expect(page.getByTestId("status-tag")).toHaveText("启用");
await expect(page.getByTestId("param-name").first()).toHaveValue("line_code");
await expect(page.getByTestId("params-table").locator(".el-table__row").nth(1).getByTestId("param-default")).toHaveValue("0");
await expect(page.getByTestId("output-name").nth(1)).toHaveValue("temperature");
await expect(page.getByTestId("identifier-tag")).toHaveText("process_readings");
await expect(page.getByTestId("field-timeout").locator("input")).toHaveValue("5000");
await expect(page.getByTestId("references-empty")).toHaveText("尚无引用");
await expect(page.getByTestId("versions-table")).toContainText("v1");
await expect(page.getByTestId("versions-table")).toContainText("admin.demo");
await expect(page.getByTestId("versions-table")).toContainText("当前生效");
const footer = page.getByTestId("query-footer");
await expect(footer).toBeVisible();
await expect(page.getByTestId("query-scroll").getByTestId("query-footer")).toHaveCount(0);
const order = ["footer-back", "footer-save", "footer-disable", "footer-preview"];
const labels = ["返回列表", "保存", "停用", "试跑预览"];
const xs: number[] = [];
for (const [index, id] of order.entries()) {
await expect(page.getByTestId(id)).toHaveText(labels[index]);
xs.push((await page.getByTestId(id).boundingBox())!.x);
}
expect([...xs].sort((a, b) => a - b)).toEqual(xs);
await expect(page.getByTestId("footer-publish")).toHaveCount(0);
await expect(page.getByTestId("versions-block").getByRole("button", { name: "发布" })).toHaveCount(0);
const footerBox = (await footer.boundingBox())!;
const first = (await page.getByTestId("footer-back").boundingBox())!;
const last = (await page.getByTestId("footer-preview").boundingBox())!;
expect(Math.abs((first.x + last.x + last.width) / 2 - (footerBox.x + footerBox.width / 2))).toBeLessThan(6);
expect(await page.getByTestId("query-scroll").evaluate((el) => el.scrollHeight > el.clientHeight)).toBe(true);
await page.getByTestId("query-scroll").evaluate((el) => el.scrollTo(0, el.scrollHeight));
const after = (await footer.boundingBox())!;
expect(after.y).toBeCloseTo(footerBox.y, 0);
expect(after.y + after.height).toBeLessThanOrEqual(520);
await page.getByTestId("query-scroll").evaluate((el) => el.scrollTo(0, 0));
await page.screenshot({ path: path.join(evidenceDir, "query-detail.png"), fullPage: true });
});
test("unsaved edits disable the preview until saved; metadata save sends PATCH", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockApi(page);
await page.goto(`/#/queries/${Q_ONE}`);
await expect(page.getByTestId("footer-preview")).toBeEnabled();
await expect(page.getByTestId("preview-dirty")).toHaveCount(0);
await page.getByTestId("field-name").locator("input").fill("产线温度采样(改)");
await expect(page.getByTestId("preview-dirty")).toContainText("未保存");
await expect(page.getByTestId("footer-preview")).toBeDisabled();
await expect(page.getByTestId("footer-preview")).toHaveAttribute("title", /先保存/);
await page.getByTestId("footer-save").click();
await expect(page.getByTestId("preview-dirty")).toHaveCount(0);
await expect(page.getByTestId("footer-preview")).toBeEnabled();
const patch = mock.requests.find((item) => item.method === "PATCH");
expect((patch!.body as Record<string, unknown>).name).toBe("产线温度采样(改)");
expect(patch!.pathname).toBe(`/queries/${Q_ONE}`);
expect(mock.requests.filter((item) => item.pathname.endsWith("/publish"))).toHaveLength(0);
});
test("saving content creates a new version; version page is read-only and can activate", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockApi(page);
await page.goto(`/#/queries/${Q_ONE}`);
await page.getByTestId("field-sql").locator("textarea").fill(`${SQL_ONE}\n-- v2`);
await page.getByTestId("footer-save").click();
await expect(page.getByTestId("versions-table")).toContainText("v2");
await expect(page.getByTestId("basic-sub")).toContainText("当前生效 v2");
const saveVersion = mock.requests.find(
(item) => item.method === "POST" && item.pathname === `/queries/${Q_ONE}/versions`,
);
expect(saveVersion).toBeTruthy();
expect((saveVersion!.body as Record<string, unknown>).sql_template).toContain("-- v2");
expect(mock.requests.filter((item) => item.pathname.endsWith("/publish"))).toHaveLength(0);
// Open v1: read-only page with activate + back to query.
await page.getByTestId("version-open-1").click();
const crumb = page.getByTestId("breadcrumb");
await expect(crumb).toContainText("详情");
await expect(crumb).toContainText("版本 v1");
await expect(page.getByTestId("version-number")).toHaveText("v1");
await expect(page.getByTestId("version-readonly-tag")).toHaveText("只读");
await expect(page.getByTestId("version-sql")).toContainText("FROM process_readings");
await expect(page.getByTestId("params-table")).toContainText("line_code");
await expect(page.getByTestId("version-limits")).toContainText("5000");
await expect(page.getByTestId("version-frozen-note")).toContainText("已冻结");
await expect(page.getByTestId("param-name")).toHaveCount(0);
await expect(page.getByTestId("field-sql")).toHaveCount(0);
await expect(page.getByTestId("footer-save")).toHaveCount(0);
await expect(page.getByTestId("footer-publish")).toHaveCount(0);
await expect(page.getByTestId("footer-back")).toHaveText("返回列表");
await expect(page.getByTestId("footer-query")).toHaveText("返回查询");
await expect(page.getByTestId("footer-activate")).toHaveText("激活此版本");
await expect(page.getByTestId("footer-preview")).toHaveText("试跑预览");
await expect(page.getByTestId("preview-target")).toContainText("版本 v1");
await page.screenshot({ path: path.join(evidenceDir, "query-version.png"), fullPage: true });
await page.getByTestId("footer-activate").click();
expect(
mock.requests.filter((item) => item.pathname === `/queries/${Q_ONE}/versions/1/activate`),
).toHaveLength(1);
await page.getByTestId("footer-query").click();
await expect(page.getByTestId("field-name")).toBeVisible();
await expect(page.getByTestId("breadcrumb")).not.toContainText("版本");
await expect(page.getByTestId("basic-sub")).toContainText("当前生效 v1");
});
test("a version preview runs that version", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockApi(page);
await page.goto(`/#/queries/${Q_ONE}/versions/1`);
await page.getByTestId("preview-param-line_code").locator("input").fill("L1");
await page.getByTestId("footer-preview").click();
await expect(page.getByTestId("preview-result")).toHaveAttribute("data-status", "success");
const call = mock.requests.find((item) => item.pathname === `/queries/${Q_ONE}/versions/1/preview`)!;
expect(call.body).toEqual({ params: { line_code: "L1", min_temp: 0 } });
});
test("preview: running, success with a masked column, parameter values sent by type", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockApi(page);
mock.preview.delayMs = 600;
await page.goto(`/#/queries/${Q_ONE}`);
await expect(page.getByTestId("preview-none")).toBeVisible();
await expect(page.getByTestId("preview-target")).toContainText("当前版本");
// Declared defaults pre-fill the inputs; a value that does not fit the type is not sent.
await expect(page.getByTestId("preview-param-min_temp").locator("input")).toHaveValue("0");
await page.getByTestId("preview-param-min_temp").locator("input").fill("abc");
await page.getByTestId("footer-preview").click();
await expect(page.getByTestId("preview-param-min_temp")).toContainText("不符");
expect(mock.requests.filter((item) => item.pathname.endsWith("/preview"))).toHaveLength(0);
await page.getByTestId("preview-param-min_temp").locator("input").fill("1.5");
await page.getByTestId("preview-param-line_code").locator("input").fill("L1");
await page.getByTestId("footer-preview").click();
await expect(page.getByTestId("preview-running")).toContainText("试跑中");
await expect(page.getByTestId("footer-preview")).toBeDisabled();
const result = page.getByTestId("preview-result");
await expect(result).toHaveAttribute("data-status", "success");
await expect(page.getByTestId("preview-table")).toContainText("LOT-1001");
await expect(page.getByTestId("preview-table")).toContainText("NULL");
await expect(page.getByTestId("masked-phone")).toHaveText("脱敏");
await expect(page.getByTestId("masked-lot_no")).toHaveCount(0);
await expect(page.getByTestId("preview-meta")).toContainText("timeout_ms=5000");
await expect(page.getByTestId("preview-meta")).toContainText("产线工艺库");
await expect(page.getByTestId("preview-meta")).toContainText("不创建报警");
const call = mock.requests.find((item) => item.pathname === `/queries/${Q_ONE}/preview`)!;
expect(call.body).toEqual({ params: { line_code: "L1", min_temp: 1.5 } });
await page.screenshot({ path: path.join(evidenceDir, "query-preview-success.png"), fullPage: true });
});
test("preview: empty, illegal type and every failure kind stay apart", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockApi(page);
await page.goto(`/#/queries/${Q_ONE}`);
const result = page.getByTestId("preview-result");
mock.preview.body = previewBody({ status: "empty", columns: ["lot_no"], rows: [], row_count: 0, masked_columns: [] });
await page.getByTestId("footer-preview").click();
await expect(result).toHaveAttribute("data-status", "empty");
await expect(result).toContainText("空结果");
await expect(result).toContainText("不是失败");
await expect(page.getByTestId("preview-table")).toHaveCount(0);
await page.screenshot({ path: path.join(evidenceDir, "query-preview-empty.png"), fullPage: true });
mock.preview.body = previewBody({
status: "illegal_type",
columns: ["temperature"],
details: { fields: [{ field: "temperature", expected: "number", actual: "str", row: 1 }] },
});
await page.getByTestId("footer-preview").click();
await expect(result).toHaveAttribute("data-status", "illegal_type");
await expect(result).toContainText("输出类型不匹配");
await expect(page.getByTestId("preview-problems")).toContainText("temperature");
await expect(page.getByTestId("preview-problems")).toContainText("number");
await expect(page.getByTestId("preview-problems")).toContainText("str");
await page.screenshot({ path: path.join(evidenceDir, "query-preview-illegal.png"), fullPage: true });
const kinds: [string, string, boolean][] = [
["timeout", "执行超时", false],
["unreachable", "连接失败", true],
["auth_failed", "认证失败", true],
["rejected", "拒绝连接", true],
["sql_error", "SQL 执行失败", false],
["limit_exceeded", "超出 max_rows", false],
["validation", "模板或参数无效", false],
];
for (const [kind, title, counted] of kinds) {
mock.preview.body = previewBody({
status: "failure",
failure_kind: kind,
message: SERVER_TEXT,
details: kind === "limit_exceeded" ? { max_rows: 200 } : kind === "validation" ? { reason: "missing_param" } : {},
});
await page.getByTestId("footer-preview").click();
await expect(result).toHaveAttribute("data-status", "failure");
await expect(result).toHaveAttribute("data-failure-kind", kind);
await expect(result).toContainText(title);
await expect(page.getByTestId("preview-failure-note")).toContainText(counted ? "会计入" : "不计入");
await expect(page.locator("body")).not.toContainText(SERVER_TEXT);
}
await expect(result).toContainText("缺少必填参数");
await page.screenshot({ path: path.join(evidenceDir, "query-preview-failure.png"), fullPage: true });
mock.preview.body = previewBody({
status: "failure",
failure_kind: "circuit_open",
details: { reason: "circuit_open", circuit_open_until: "2026-11-18T09:30:00+00:00" },
});
await page.getByTestId("footer-preview").click();
await expect(result).toHaveAttribute("data-status", "circuit_open");
await expect(result).toContainText("熔断中");
await expect(result).toContainText("2026-11-18");
mock.preview.body = previewBody({ status: "failure", failure_kind: "disabled", details: { reason: "disabled" } });
await page.getByTestId("footer-preview").click();
await expect(result).toHaveAttribute("data-status", "disabled");
await expect(result).toContainText("数据源已停用");
mock.preview = { status: 403, delayMs: 0, body: fail(42000, SERVER_TEXT, { permission_node: "x" }) };
await page.getByTestId("footer-preview").click();
await expect(page.getByTestId("preview-error")).toContainText("权限不足");
await expect(page.locator("body")).not.toContainText(SERVER_TEXT);
});
test("disabled query: the button stays clickable and the 409 is explained", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockApi(page);
await page.goto(`/#/queries/${Q_OFF}`);
await expect(page.getByTestId("query-disabled-note")).toBeVisible();
await expect(page.getByTestId("footer-enable")).toHaveText("启用");
await expect(page.getByTestId("footer-disable")).toHaveCount(0);
await expect(page.getByTestId("footer-preview")).toBeEnabled();
await page.getByTestId("footer-preview").click();
const result = page.getByTestId("preview-result");
await expect(result).toHaveAttribute("data-status", "disabled");
await expect(result).toContainText("该查询已停用");
await expect(page.locator("body")).not.toContainText("Query is disabled");
expect(mock.requests.filter((item) => item.pathname.endsWith("/preview"))).toHaveLength(1);
await page.screenshot({ path: path.join(evidenceDir, "query-disabled.png"), fullPage: true });
});
test("停用 asks to confirm, 启用 does not; the list follows", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockApi(page);
await page.goto(`/#/queries/${Q_ONE}`);
await page.getByTestId("footer-disable").click();
await page.locator(".el-message-box__btns .el-button:not(.el-button--primary)").click();
expect(mock.requests.filter((item) => item.pathname.endsWith("/disable"))).toHaveLength(0);
await page.getByTestId("footer-disable").click();
await confirmDialog(page);
await expect(page.getByTestId("footer-enable")).toHaveText("启用");
await expect(page.getByTestId("query-disabled-note")).toBeVisible();
await expect(page.getByTestId("status-tag")).toHaveText("已停用");
await page.getByTestId("footer-back").click();
await expect(page.getByTestId(`query-row-${Q_ONE}`).getByTestId("row-preview")).toBeDisabled();
await page.getByTestId(`query-row-${Q_ONE}`).getByTestId("row-open").click();
await page.getByTestId("footer-enable").click();
await expect(page.getByTestId("footer-disable")).toBeVisible();
await expect(page.getByTestId("query-disabled-note")).toHaveCount(0);
expect(mock.requests.filter((item) => item.pathname.endsWith("/enable"))).toHaveLength(1);
});
test("list 预览 opens the detail at the trial-run panel without running it", async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 520 });
await signIn(page, ["watchman-admin"]);
const mock = await mockApi(page);
await page.goto("/#/queries");
await page.getByTestId(`query-row-${Q_ONE}`).getByTestId("row-preview").click();
await expect(page.getByTestId("preview-card")).toBeInViewport();
await expect(page.getByTestId("preview-none")).toBeVisible();
expect(mock.requests.filter((item) => item.pathname.endsWith("/preview"))).toHaveLength(0);
});
test("unknown query and version show a not-found message", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
await mockApi(page);
await page.goto("/#/queries/99999999-9999-4999-8999-999999999999");
await expect(page.getByTestId("query-load-error")).toContainText("查询不存在");
await expect(page.getByTestId("footer-back")).toBeVisible();
await expect(page.getByTestId("footer-save")).toHaveCount(0);
await page.goto(`/#/queries/${Q_ONE}/versions/9`);
await expect(page.getByTestId("query-load-error")).toContainText("版本不存在");
});
});
+292 -6
View File
@@ -1,9 +1,9 @@
{
"appName": "Watchman",
"appName": "Alert Platform",
"login": {
"title": "Sign in to Watchman",
"title": "Sign in to Alert Platform",
"subtitle": "Use your company account to open the alert platform",
"eyebrow": "WATCHMAN · EARLY WARNING",
"eyebrow": "ALERT PLATFORM · EARLY WARNING",
"heroEm": "visible",
"heroBefore": "Make exceptions ",
"submitting": "Signing in",
@@ -20,7 +20,7 @@
"unavailable": "Sign-in is temporarily unavailable. Try again shortly.",
"logout": "Sign out",
"forbiddenTitle": "No access",
"forbiddenBody": "This account is signed in, but it does not have a Watchman view, operate, or admin role.",
"forbiddenBody": "This account is signed in, but it does not have an Alert Platform view, operate, or admin role.",
"fixture": "Local identity mode. This is not a production sign-in."
},
"shell": {
@@ -36,8 +36,10 @@
"nav": {
"home": "Overview",
"datasources": "Data sources",
"queries": "Queries",
"create": "New",
"detail": "Details"
"detail": "Details",
"version": "Version v{no}"
},
"datasource": {
"list": {
@@ -45,7 +47,15 @@
"loading": "Loading data sources",
"loadFailed": "Failed to load data sources",
"empty": "No data sources yet",
"emptyHint": "An administrator can create the first data source."
"emptyHint": "An administrator can create the first data source.",
"filterName": "Name (contains)",
"filterEngine": "Engine",
"filterStatus": "Status",
"filterSearch": "Search",
"filterReset": "Reset",
"filterClear": "Clear filters",
"filterEmpty": "No data sources match",
"filterEmptyHint": "Try another name, engine or status, or reset the filters."
},
"columns": {
"name": "Name",
@@ -166,5 +176,281 @@
},
"saved": "Saved",
"disabled": "Disabled"
},
"query": {
"list": {
"create": "New",
"loadFailed": "Failed to load queries",
"empty": "No queries yet",
"emptyHint": "An administrator can create the first query: pick a data source, write a parameterized SQL template, and declare its parameters and output contract.",
"filterName": "Name (contains)",
"filterDatasource": "Data source",
"filterStatus": "Status",
"filterSearch": "Search",
"filterReset": "Reset",
"filterClear": "Clear filters",
"filterEmpty": "No queries match",
"filterEmptyHint": "Try another name, data source or status, or reset the filters."
},
"columns": {
"name": "Name",
"datasource": "Data source",
"status": "Status",
"latestVersion": "Latest version",
"currentVersion": "Current version",
"updatedAt": "Updated",
"actions": "Actions"
},
"status": {
"enabled": "Enabled",
"disabled": "Disabled"
},
"actions": {
"open": "Open",
"preview": "Preview",
"previewDisabledWhy": "Disabled, cannot be previewed",
"backToList": "Back to list",
"backToDraft": "Back to query",
"backToQuery": "Back to query",
"save": "Save",
"publish": "Publish",
"activate": "Activate this version",
"switchVersion": "Switch version",
"needSave": "Save the draft first",
"disable": "Disable",
"enable": "Enable",
"runPreview": "Run preview",
"previewNeedSave": "Save first; preview uses the saved current version",
"add": "Add",
"remove": "Remove"
},
"denied": {
"title": "Queries are not available",
"body": "Only administrators can open the query pages."
},
"form": {
"basic": "Basics",
"subNew": "New",
"subSaved": "Current {version}",
"name": "Name",
"namePlaceholder": "Unique within the tenant",
"nameTooLong": "At most 128 characters",
"datasource": "Data source",
"datasourcePlaceholder": "Select a data source",
"datasourceOff": "(disabled)",
"datasourcesFailed": "Failed to load data sources",
"description": "Purpose",
"status": "Status",
"statusNew": "Enabled by default after creation",
"statusHint": "Switch it with {action} in the footer",
"sql": "SQL template",
"sqlPlaceholder": "SELECT lot_no FROM process_readings WHERE line_code = :line_code",
"sqlHint": "Use named parameters such as :line_code. Values are always bound, never spliced into the SQL. Read-only access is guaranteed by the data source account and the executor.",
"paramsTitle": "Parameter schema",
"paramsHint": "Every :name in the SQL must be declared here. Undeclared parameters are refused when running or publishing.",
"outputsTitle": "Output schema",
"outputsHint": "The output contract used to check result types: names and types only.",
"identifiersTitle": "Allowed identifiers",
"identifiersHint": "Table or column names cannot be parameter values. Only names declared here may appear in the template at {example}. Empty means none are allowed.",
"limits": "Execution limits",
"limitsHint": "Server caps: timeout_ms up to {timeout}, max_rows up to {rows}.",
"required": "Required",
"invalidRange": "Enter a whole number from {min} to {max}"
},
"sqlParams": {
"none": "No :parameters used in the SQL yet.",
"used": "Parameters in the SQL:",
"undeclared": ":{name} not declared",
"undeclaredTitle": "Not declared in the parameter schema; preview and save will reject it",
"unused": "{name} unused",
"unusedTitle": "Declared but not used in the SQL"
},
"params": {
"name": "Name",
"type": "Type",
"required": "Required",
"default": "Default",
"yes": "Yes",
"no": "No",
"add": "Add parameter",
"empty": "No parameters declared yet.",
"namePlaceholder": "For example line_code",
"defaultPlaceholder": "Optional",
"invalidName": "Invalid parameter name: {name}",
"duplicate": "Duplicate parameter name: {name}",
"invalidDefault": "Default does not fit the type: {name}"
},
"outputs": {
"name": "Column",
"type": "Type",
"add": "Add output column",
"empty": "No output columns declared yet.",
"namePlaceholder": "For example lot_no",
"invalidName": "Invalid output column name: {name}",
"duplicate": "Duplicate output column name: {name}",
"invalidDefault": "Invalid output column: {name}"
},
"identifiers": {
"none": "None (dynamic identifiers are not allowed)",
"placeholder": "Type an identifier and press Enter, for example process_readings",
"invalid": "An identifier may only contain letters, digits and underscores, and cannot start with a digit: {name}"
},
"preview": {
"title": "Trial run",
"target": "Preview target: ",
"targetVersion": "Version v{no} (frozen)",
"dirtyNote": "You have unsaved changes. Save before running a preview (it uses the saved current version).",
"needSaveNote": "Save before running a preview.",
"noParams": "This query declares no parameters, so you can run it directly.",
"invalidValue": "The value does not fit the parameter type",
"unset": "(not set)",
"none": "Not run yet. Fill in the parameters and use Run preview in the footer.",
"running": "Running",
"success": {
"title": "Run succeeded",
"body": "Returned {count} sample rows and the columns fit the output contract. Columns tagged Masked are covered."
},
"empty": {
"title": "Empty result",
"body": "The query ran successfully but no row matched. This is neither a failure nor a type error."
},
"illegal": {
"title": "Output type mismatch",
"body": "The query ran, but the returned values do not fit the output contract, so the whole batch is not valid output.",
"row": "Row",
"field": "Column",
"expected": "Contract type",
"actual": "Actual type"
},
"failure": {
"timeout": {
"title": "Timed out",
"body": "No answer within timeout_ms, so the query was stopped. Narrow the time window or adjust the limits and retry."
},
"unreachable": {
"title": "Connection failed",
"body": "Could not connect to the data source. Check the data source and the network."
},
"auth_failed": {
"title": "Data source authentication failed",
"body": "The data source did not accept the saved account or password. Update it on the data source page."
},
"rejected": {
"title": "Data source refused the connection",
"body": "The data source replied but refused the connection, for example because the database does not exist."
},
"sql_error": {
"title": "SQL failed",
"body": "The source database rejected the SQL. Check the SQL template."
},
"limit_exceeded": {
"title": "Over max_rows",
"body": "More rows than max_rows={max_rows} were returned, so nothing was returned. Narrow the condition or raise max_rows."
},
"validation": {
"title": "Template or parameters invalid",
"body": "The template or parameters failed validation, so nothing was sent to the source database."
},
"engine_readonly_unsupported": {
"title": "Preview not available for this engine",
"body": "SQL Server has no server-enforced read-only session in this release, so query preview is refused. Use a PostgreSQL or MySQL data source; connection tests still work."
},
"unknown": {
"title": "Run failed",
"body": "The query did not complete."
},
"noteCircuit": "Connection-class failures count toward this data source's circuit breaker.",
"noteNoCircuit": "This kind of failure does not count toward the circuit breaker."
},
"disabled": {
"title": "Disabled, not run",
"queryBody": "This query is disabled and cannot be run. Use Enable in the footer first.",
"sourceBody": "The bound data source is disabled and cannot be run."
},
"circuit": {
"title": "Data source circuit open, not run",
"body": "The data source circuit is open, so no query is sent to the source database. Expected to recover after {until}."
},
"masked": "Masked",
"datasource": "Data source {name}",
"onlyPreview": "Preview only: no alarm is created, no notification is sent, nothing enters official runs.",
"failedUnknown": "The run did not finish. Try again shortly.",
"targetCurrent": "Current version (saved content)"
},
"versions": {
"title": "Versions",
"hint": "Saving creates a new version and makes it current. Any history version can be activated.",
"empty": "No versions yet.",
"emptyCreate": "After you save, v1 will appear here.",
"version": "Version",
"latest": "Latest",
"current": "Current",
"publishedAt": "Created at",
"publishedBy": "By",
"unpublished": "No version",
"none": "None",
"loadFailed": "Failed to load versions",
"frozenNote": "Version {version} is frozen and cannot be edited. Fix it on the query page and save a new version; you can still preview or activate here.",
"info": "Version info",
"readonly": "Read-only",
"query": "Query",
"activated": "Switched to {version}",
"switchTitle": "Switch version · {name}"
},
"refs": {
"title": "References",
"empty": "No references yet",
"loadFailed": "Failed to load references"
},
"publishConfirm": {
"title": "Publish {version}?",
"body": "The saved draft will be frozen as immutable version {version}. It cannot be changed or deleted afterwards; a correction needs a new version.",
"ok": "Publish",
"cancel": "Cancel"
},
"disableConfirm": {
"title": "Disable query",
"body": "A disabled query cannot be previewed. The record and published versions are kept. Disable \"{name}\"?",
"ok": "Disable",
"cancel": "Cancel"
},
"disabledNote": "This query is disabled. You can still view and edit the draft, but not run a preview. Use Enable in the footer to restore it.",
"notFound": "Query not found",
"versionNotFound": "Version not found",
"loadFailed": "Failed to load the query",
"saveFailed": "The action did not complete. Try again shortly.",
"saved": "Draft saved",
"savedVersion": "Saved as {version} and set as current",
"publishNeedSave": "Save unsaved changes first",
"published": "Saved {version}",
"enabledDone": "Enabled",
"disabledDone": "Disabled",
"errors": {
"duplicate_name": "This name already exists. Choose another.",
"datasource_not_found": "The selected data source does not exist",
"datasource_not_database": "Only a database data source can be used",
"template_empty": "The SQL template cannot be empty",
"param_schema_invalid": "The parameter schema is invalid",
"param_default_invalid": "A parameter default does not fit its type",
"output_schema_invalid": "The output schema is invalid",
"allowed_identifiers_invalid": "The allowed identifiers are invalid",
"limit_invalid": "A limit must be a whole number of at least 1",
"disabled": "The query is disabled and cannot be run",
"version_conflict": "Version number conflict. Refresh and try again.",
"not_found": "Record not found",
"version_immutable": "A published version cannot be changed",
"identifier_invalid": "An identifier in the template is malformed",
"identifier_not_allowed": "The template uses an identifier that is not allowed",
"identifier_unterminated": "An identifier in the template is not closed",
"missing_param": "A required parameter is missing",
"multiple_statements": "The template may contain only one statement",
"param_type_mismatch": "A parameter value does not fit its type",
"params_invalid": "The parameters are malformed",
"template_unterminated": "The template has an unclosed quote or comment",
"undeclared_param": "The template uses a parameter that is not declared",
"unknown_param": "A parameter that is not declared was sent",
"unsupported_engine": "This data source engine is not supported yet",
"unsupported_datasource": "This data source type is not supported yet"
}
}
}
+292 -6
View File
@@ -1,9 +1,9 @@
{
"appName": "Watchman",
"appName": "แพลตฟอร์มแจ้งเตือน",
"login": {
"title": "เข้าสู่ Watchman",
"title": "เข้าสู่แพลตฟอร์มแจ้งเตือน",
"subtitle": "ใช้บัญชีบริษัทเพื่อเข้าสู่แพลตฟอร์มแจ้งเตือน",
"eyebrow": "WATCHMAN · EARLY WARNING",
"eyebrow": "แพลตฟอร์มแจ้งเตือน · EARLY WARNING",
"heroEm": "เห็นได้",
"heroBefore": "ทำให้ความผิดปกติ",
"submitting": "กำลังเข้าสู่ระบบ",
@@ -20,7 +20,7 @@
"unavailable": "บริการเข้าสู่ระบบไม่พร้อมชั่วคราว โปรดลองอีกครั้ง",
"logout": "ออกจากระบบ",
"forbiddenTitle": "ไม่มีสิทธิ์เข้าใช้",
"forbiddenBody": "บัญชีนี้เข้าสู่ระบบแล้ว แต่ไม่มีบทบาทดู ดำเนินการ หรือผู้ดูแลของ Watchman",
"forbiddenBody": "บัญชีนี้เข้าสู่ระบบแล้ว แต่ไม่มีบทบาทดู ดำเนินการ หรือผู้ดูแลของแพลตฟอร์มแจ้งเตือน",
"fixture": "โหมดตัวตนภายในเครื่อง ไม่ใช่การเข้าสู่ระบบจริง"
},
"shell": {
@@ -36,8 +36,10 @@
"nav": {
"home": "ภาพรวม",
"datasources": "แหล่งข้อมูล",
"queries": "คิวรี",
"create": "สร้างใหม่",
"detail": "รายละเอียด"
"detail": "รายละเอียด",
"version": "เวอร์ชัน v{no}"
},
"datasource": {
"list": {
@@ -45,7 +47,15 @@
"loading": "กำลังโหลดแหล่งข้อมูล",
"loadFailed": "โหลดแหล่งข้อมูลไม่สำเร็จ",
"empty": "ยังไม่มีแหล่งข้อมูล",
"emptyHint": "ผู้ดูแลสามารถสร้างแหล่งข้อมูลแรกได้"
"emptyHint": "ผู้ดูแลสามารถสร้างแหล่งข้อมูลแรกได้",
"filterName": "ชื่อ (ค้นหาบางส่วน)",
"filterEngine": "เอนจิน",
"filterStatus": "สถานะ",
"filterSearch": "ค้นหา",
"filterReset": "รีเซ็ต",
"filterClear": "ล้างตัวกรอง",
"filterEmpty": "ไม่มีแหล่งข้อมูลที่ตรงเงื่อนไข",
"filterEmptyHint": "ลองเปลี่ยนชื่อ เอนจิน หรือสถานะ หรือกดรีเซ็ต"
},
"columns": {
"name": "ชื่อ",
@@ -166,5 +176,281 @@
},
"saved": "บันทึกแล้ว",
"disabled": "ปิดใช้งานแล้ว"
},
"query": {
"list": {
"create": "สร้างใหม่",
"loadFailed": "โหลดคิวรีไม่สำเร็จ",
"empty": "ยังไม่มีคิวรี",
"emptyHint": "ผู้ดูแลสามารถสร้างคิวรีแรกได้ โดยเลือกแหล่งข้อมูล เขียนเทมเพลต SQL แบบมีพารามิเตอร์ และประกาศพารามิเตอร์กับสัญญาเอาต์พุต",
"filterName": "ชื่อ (ค้นหาบางส่วน)",
"filterDatasource": "แหล่งข้อมูล",
"filterStatus": "สถานะ",
"filterSearch": "ค้นหา",
"filterReset": "รีเซ็ต",
"filterClear": "ล้างตัวกรอง",
"filterEmpty": "ไม่มีคิวรีที่ตรงเงื่อนไข",
"filterEmptyHint": "ลองเปลี่ยนชื่อ แหล่งข้อมูล หรือสถานะ หรือกดรีเซ็ต"
},
"columns": {
"name": "ชื่อ",
"datasource": "แหล่งข้อมูล",
"status": "สถานะ",
"latestVersion": "เวอร์ชันล่าสุด",
"currentVersion": "เวอร์ชันปัจจุบัน",
"updatedAt": "อัปเดตเมื่อ",
"actions": "การดำเนินการ"
},
"status": {
"enabled": "เปิดใช้งาน",
"disabled": "ปิดใช้งานแล้ว"
},
"actions": {
"open": "เปิด",
"preview": "ตัวอย่าง",
"previewDisabledWhy": "ปิดใช้งานแล้ว ดูตัวอย่างไม่ได้",
"backToList": "กลับไปที่รายการ",
"backToDraft": "กลับไปที่คิวรี",
"backToQuery": "กลับไปที่คิวรี",
"save": "บันทึก",
"publish": "เผยแพร่",
"activate": "เปิดใช้เวอร์ชันนี้",
"switchVersion": "สลับเวอร์ชัน",
"needSave": "บันทึกฉบับร่างก่อน",
"disable": "ปิดใช้งาน",
"enable": "เปิดใช้งาน",
"runPreview": "ทดลองรันตัวอย่าง",
"previewNeedSave": "บันทึกก่อน ตัวอย่างใช้เวอร์ชันปัจจุบันที่บันทึกแล้ว",
"add": "เพิ่ม",
"remove": "ลบ"
},
"denied": {
"title": "ไม่สามารถเข้าถึงคิวรี",
"body": "เฉพาะผู้ดูแลเท่านั้นที่เปิดหน้าคิวรีได้"
},
"form": {
"basic": "ข้อมูลพื้นฐาน",
"subNew": "สร้างใหม่",
"subSaved": "ใช้งานอยู่ {version}",
"name": "ชื่อ",
"namePlaceholder": "ไม่ซ้ำภายในผู้เช่า",
"nameTooLong": "ยาวได้ไม่เกิน 128 ตัวอักษร",
"datasource": "แหล่งข้อมูล",
"datasourcePlaceholder": "เลือกแหล่งข้อมูล",
"datasourceOff": "(ปิดใช้งานแล้ว)",
"datasourcesFailed": "โหลดแหล่งข้อมูลไม่สำเร็จ",
"description": "วัตถุประสงค์",
"status": "สถานะ",
"statusNew": "เปิดใช้งานโดยค่าเริ่มต้นหลังสร้าง",
"statusHint": "สลับได้ด้วย {action} ที่ส่วนท้ายหน้า",
"sql": "เทมเพลต SQL",
"sqlPlaceholder": "SELECT lot_no FROM process_readings WHERE line_code = :line_code",
"sqlHint": "ใช้พารามิเตอร์แบบมีชื่อ เช่น :line_code ค่าจะถูกผูกเสมอ ไม่ถูกต่อเข้ากับ SQL การอ่านอย่างเดียวรับประกันโดยบัญชีแหล่งข้อมูลและตัวรัน",
"paramsTitle": "สคีมาพารามิเตอร์",
"paramsHint": ":name ทุกตัวใน SQL ต้องประกาศที่นี่ พารามิเตอร์ที่ไม่ได้ประกาศจะถูกปฏิเสธเมื่อรันหรือเผยแพร่",
"outputsTitle": "สคีมาเอาต์พุต",
"outputsHint": "สัญญาเอาต์พุตสำหรับตรวจชนิดผลลัพธ์ มีเพียงชื่อและชนิด",
"identifiersTitle": "ตัวระบุที่อนุญาต",
"identifiersHint": "ชื่อตารางหรือคอลัมน์ใช้เป็นค่าพารามิเตอร์ไม่ได้ เฉพาะชื่อที่ประกาศที่นี่เท่านั้นที่ปรากฏในเทมเพลตที่ตำแหน่ง {example} ได้ ว่างไว้หมายถึงไม่อนุญาต",
"limits": "ขีดจำกัดการรัน",
"limitsHint": "เซิร์ฟเวอร์จำกัด: timeout_ms ไม่เกิน {timeout}, max_rows ไม่เกิน {rows}",
"required": "จำเป็น",
"invalidRange": "ต้องเป็นจำนวนเต็มตั้งแต่ {min} ถึง {max}"
},
"sqlParams": {
"none": "ยังไม่มีพารามิเตอร์ :name ใน SQL",
"used": "พารามิเตอร์ใน SQL:",
"undeclared": ":{name} ยังไม่ได้ประกาศ",
"undeclaredTitle": "ยังไม่ได้ประกาศใน parameter schema ตัวอย่างและการบันทึกจะถูกปฏิเสธ",
"unused": "{name} ไม่ได้ใช้",
"unusedTitle": "ประกาศไว้แต่ไม่ได้ใช้ใน SQL"
},
"params": {
"name": "ชื่อ",
"type": "ชนิด",
"required": "จำเป็น",
"default": "ค่าเริ่มต้น",
"yes": "ใช่",
"no": "ไม่",
"add": "เพิ่มพารามิเตอร์",
"empty": "ยังไม่ได้ประกาศพารามิเตอร์",
"namePlaceholder": "เช่น line_code",
"defaultPlaceholder": "เว้นว่างได้",
"invalidName": "ชื่อพารามิเตอร์ไม่ถูกต้อง: {name}",
"duplicate": "ชื่อพารามิเตอร์ซ้ำ: {name}",
"invalidDefault": "ค่าเริ่มต้นไม่ตรงกับชนิด: {name}"
},
"outputs": {
"name": "คอลัมน์",
"type": "ชนิด",
"add": "เพิ่มคอลัมน์เอาต์พุต",
"empty": "ยังไม่ได้ประกาศคอลัมน์เอาต์พุต",
"namePlaceholder": "เช่น lot_no",
"invalidName": "ชื่อคอลัมน์เอาต์พุตไม่ถูกต้อง: {name}",
"duplicate": "ชื่อคอลัมน์เอาต์พุตซ้ำ: {name}",
"invalidDefault": "คอลัมน์เอาต์พุตไม่ถูกต้อง: {name}"
},
"identifiers": {
"none": "ไม่มี (ไม่อนุญาตตัวระบุแบบไดนามิก)",
"placeholder": "พิมพ์ตัวระบุแล้วกด Enter เช่น process_readings",
"invalid": "ตัวระบุมีได้เฉพาะตัวอักษร ตัวเลข และขีดล่าง และห้ามขึ้นต้นด้วยตัวเลข: {name}"
},
"preview": {
"title": "ทดลองรันตัวอย่าง",
"target": "เป้าหมายตัวอย่าง: ",
"targetVersion": "เวอร์ชัน v{no} (ล็อกแล้ว)",
"dirtyNote": "มีการแก้ไขที่ยังไม่บันทึก บันทึกก่อนรันตัวอย่าง (ใช้เวอร์ชันปัจจุบันที่บันทึกแล้ว)",
"needSaveNote": "บันทึกก่อนจึงจะรันตัวอย่างได้",
"noParams": "คิวรีนี้ไม่ได้ประกาศพารามิเตอร์ จึงรันได้ทันที",
"invalidValue": "ค่าไม่ตรงกับชนิดพารามิเตอร์",
"unset": "(ยังไม่ระบุ)",
"none": "ยังไม่ได้รัน กรอกพารามิเตอร์แล้วกด ทดลองรันตัวอย่าง ที่ส่วนท้ายหน้า",
"running": "กำลังรัน",
"success": {
"title": "รันสำเร็จ",
"body": "ส่งคืน {count} แถวตัวอย่าง และคอลัมน์ตรงตามสัญญาเอาต์พุต คอลัมน์ที่ติดป้ายปกปิดถูกบดบังแล้ว"
},
"empty": {
"title": "ผลลัพธ์ว่าง",
"body": "คิวรีรันสำเร็จแต่ไม่มีแถวที่ตรงเงื่อนไข ไม่ใช่ความล้มเหลวและไม่ใช่ข้อผิดพลาดด้านชนิด"
},
"illegal": {
"title": "ชนิดเอาต์พุตไม่ตรง",
"body": "คิวรีรันแล้ว แต่ค่าที่ส่งคืนไม่ตรงกับสัญญาเอาต์พุต ผลลัพธ์ทั้งชุดจึงไม่ถือว่าถูกต้อง",
"row": "แถว",
"field": "คอลัมน์",
"expected": "ชนิดตามสัญญา",
"actual": "ชนิดจริง"
},
"failure": {
"timeout": {
"title": "หมดเวลา",
"body": "ไม่มีการตอบกลับภายใน timeout_ms จึงยกเลิกคิวรี ลองลดช่วงเวลาหรือปรับขีดจำกัดแล้วลองใหม่"
},
"unreachable": {
"title": "เชื่อมต่อไม่สำเร็จ",
"body": "เชื่อมต่อแหล่งข้อมูลไม่ได้ โปรดตรวจสอบแหล่งข้อมูลและเครือข่าย"
},
"auth_failed": {
"title": "การยืนยันตัวตนกับแหล่งข้อมูลล้มเหลว",
"body": "แหล่งข้อมูลไม่ยอมรับบัญชีหรือรหัสผ่านที่บันทึกไว้ โปรดอัปเดตที่หน้าแหล่งข้อมูล"
},
"rejected": {
"title": "แหล่งข้อมูลปฏิเสธการเชื่อมต่อ",
"body": "แหล่งข้อมูลตอบกลับแต่ปฏิเสธการเชื่อมต่อ เช่น ไม่มีฐานข้อมูลชื่อนี้"
},
"sql_error": {
"title": "SQL ทำงานล้มเหลว",
"body": "ฐานข้อมูลต้นทางปฏิเสธ SQL นี้ โปรดตรวจสอบเทมเพลต SQL"
},
"limit_exceeded": {
"title": "เกิน max_rows",
"body": "ส่งคืนแถวมากกว่า max_rows={max_rows} จึงไม่ส่งคืนอะไรเลย ลองจำกัดเงื่อนไขหรือเพิ่ม max_rows"
},
"validation": {
"title": "เทมเพลตหรือพารามิเตอร์ไม่ถูกต้อง",
"body": "เทมเพลตหรือพารามิเตอร์ไม่ผ่านการตรวจสอบ จึงไม่ได้ส่งอะไรไปยังฐานข้อมูลต้นทาง"
},
"engine_readonly_unsupported": {
"title": "เอนจินนี้ยังไม่รองรับการทดลองรัน",
"body": "SQL Server ยังไม่มีเซสชันแบบบังคับอ่านอย่างเดียวในรุ่นนี้ จึงไม่รันพรีวิวคิวรี โปรดใช้แหล่งข้อมูล PostgreSQL หรือ MySQL ส่วนการทดสอบการเชื่อมต่อยังใช้ได้"
},
"unknown": {
"title": "การรันล้มเหลว",
"body": "คิวรีทำงานไม่เสร็จ"
},
"noteCircuit": "ความล้มเหลวประเภทการเชื่อมต่อจะนับรวมในสถิติเบรกเกอร์ของแหล่งข้อมูลนี้",
"noteNoCircuit": "ความล้มเหลวประเภทนี้ไม่นับรวมในสถิติเบรกเกอร์"
},
"disabled": {
"title": "ปิดใช้งานแล้ว ไม่ได้รัน",
"queryBody": "คิวรีนี้ปิดใช้งานแล้วจึงรันไม่ได้ โปรดกด เปิดใช้งาน ที่ส่วนท้ายหน้าก่อน",
"sourceBody": "แหล่งข้อมูลที่ผูกไว้ปิดใช้งานแล้วจึงรันไม่ได้"
},
"circuit": {
"title": "เบรกเกอร์ของแหล่งข้อมูลเปิดอยู่ ไม่ได้รัน",
"body": "เบรกเกอร์ของแหล่งข้อมูลเปิดอยู่ จึงไม่ส่งคิวรีไปยังฐานข้อมูลต้นทาง คาดว่าจะกลับมาหลัง {until}"
},
"masked": "ปกปิด",
"datasource": "แหล่งข้อมูล {name}",
"onlyPreview": "ดูตัวอย่างเท่านั้น: ไม่สร้างการแจ้งเตือน ไม่ส่งการแจ้ง และไม่เข้าสู่การรันจริง",
"failedUnknown": "การรันไม่เสร็จสิ้น โปรดลองใหม่ภายหลัง",
"targetCurrent": "เวอร์ชันปัจจุบัน (เนื้อหาที่บันทึกแล้ว)"
},
"versions": {
"title": "เวอร์ชัน",
"hint": "การบันทึกจะสร้างเวอร์ชันใหม่และตั้งเป็นปัจจุบัน สามารถเปิดใช้เวอร์ชันย้อนหลังได้",
"empty": "ยังไม่มีเวอร์ชัน",
"emptyCreate": "หลังบันทึก v1 จะปรากฏที่นี่",
"version": "เวอร์ชัน",
"latest": "ล่าสุด",
"current": "ใช้งานอยู่",
"publishedAt": "สร้างเมื่อ",
"publishedBy": "โดย",
"unpublished": "ไม่มีเวอร์ชัน",
"none": "ไม่มี",
"loadFailed": "โหลดรายการเวอร์ชันไม่สำเร็จ",
"frozenNote": "เวอร์ชัน {version} ถูกแช่แข็ง แก้ไขที่หน้าคิวรีแล้วบันทึกเป็นเวอร์ชันใหม่ ที่นี่ยังดูตัวอย่างหรือเปิดใช้ได้",
"info": "ข้อมูลเวอร์ชัน",
"readonly": "อ่านอย่างเดียว",
"query": "คิวรี",
"activated": "สลับเป็น {version} แล้ว",
"switchTitle": "สลับเวอร์ชัน · {name}"
},
"refs": {
"title": "การอ้างอิง",
"empty": "ยังไม่มีการอ้างอิง",
"loadFailed": "โหลดการอ้างอิงไม่สำเร็จ"
},
"publishConfirm": {
"title": "ยืนยันเผยแพร่ {version}?",
"body": "ฉบับร่างที่บันทึกไว้จะถูกล็อกเป็นเวอร์ชัน {version} ที่แก้ไขไม่ได้ หลังเผยแพร่จะแก้ไขหรือลบไม่ได้ หากต้องการแก้ต้องเผยแพร่เวอร์ชันใหม่",
"ok": "เผยแพร่",
"cancel": "ยกเลิก"
},
"disableConfirm": {
"title": "ปิดใช้งานคิวรี",
"body": "คิวรีที่ปิดใช้งานจะดูตัวอย่างไม่ได้ ระเบียนและเวอร์ชันที่เผยแพร่แล้วยังคงอยู่ ปิดใช้งาน \"{name}\" หรือไม่?",
"ok": "ปิดใช้งาน",
"cancel": "ยกเลิก"
},
"disabledNote": "คิวรีนี้ปิดใช้งานแล้ว ยังดูและแก้ไขฉบับร่างได้ แต่ทดลองรันตัวอย่างไม่ได้ กด เปิดใช้งาน ที่ส่วนท้ายหน้าเพื่อกู้คืน",
"notFound": "ไม่พบคิวรี",
"versionNotFound": "ไม่พบเวอร์ชัน",
"loadFailed": "โหลดคิวรีไม่สำเร็จ",
"saveFailed": "การดำเนินการไม่เสร็จสิ้น โปรดลองใหม่ภายหลัง",
"saved": "บันทึกฉบับร่างแล้ว",
"savedVersion": "บันทึกเป็น {version} และตั้งเป็นปัจจุบันแล้ว",
"publishNeedSave": "มีการแก้ไขที่ยังไม่บันทึก กรุณาบันทึกก่อน",
"published": "บันทึก {version} แล้ว",
"enabledDone": "เปิดใช้งานแล้ว",
"disabledDone": "ปิดใช้งานแล้ว",
"errors": {
"duplicate_name": "ชื่อนี้มีอยู่แล้ว โปรดใช้ชื่ออื่น",
"datasource_not_found": "ไม่พบแหล่งข้อมูลที่เลือก",
"datasource_not_database": "ใช้ได้เฉพาะแหล่งข้อมูลประเภทฐานข้อมูล",
"template_empty": "เทมเพลต SQL ต้องไม่ว่าง",
"param_schema_invalid": "สคีมาพารามิเตอร์ไม่ถูกต้อง",
"param_default_invalid": "ค่าเริ่มต้นของพารามิเตอร์ไม่ตรงกับชนิด",
"output_schema_invalid": "สคีมาเอาต์พุตไม่ถูกต้อง",
"allowed_identifiers_invalid": "ตัวระบุที่อนุญาตไม่ถูกต้อง",
"limit_invalid": "ขีดจำกัดต้องเป็นจำนวนเต็มตั้งแต่ 1 ขึ้นไป",
"disabled": "คิวรีปิดใช้งานแล้ว รันไม่ได้",
"version_conflict": "หมายเลขเวอร์ชันขัดแย้ง โปรดรีเฟรชแล้วลองใหม่",
"not_found": "ไม่พบระเบียน",
"version_immutable": "เวอร์ชันที่เผยแพร่แล้วแก้ไขไม่ได้",
"identifier_invalid": "ตัวระบุในเทมเพลตเขียนไม่ถูกต้อง",
"identifier_not_allowed": "เทมเพลตใช้ตัวระบุที่ไม่ได้รับอนุญาต",
"identifier_unterminated": "ตัวระบุในเทมเพลตไม่ได้ปิด",
"missing_param": "ขาดพารามิเตอร์ที่จำเป็น",
"multiple_statements": "เทมเพลตมีได้เพียงหนึ่งคำสั่ง",
"param_type_mismatch": "ค่าพารามิเตอร์ไม่ตรงกับชนิด",
"params_invalid": "รูปแบบพารามิเตอร์ไม่ถูกต้อง",
"template_unterminated": "เทมเพลตมีเครื่องหมายคำพูดหรือคอมเมนต์ที่ไม่ปิด",
"undeclared_param": "เทมเพลตใช้พารามิเตอร์ที่ไม่ได้ประกาศ",
"unknown_param": "ส่งพารามิเตอร์ที่ไม่ได้ประกาศมา",
"unsupported_engine": "ยังไม่รองรับเอนจินของแหล่งข้อมูลนี้",
"unsupported_datasource": "ยังไม่รองรับแหล่งข้อมูลประเภทนี้"
}
}
}
+292 -6
View File
@@ -1,9 +1,9 @@
{
"appName": "Watchman",
"appName": "预警平台",
"login": {
"title": "登录 Watchman",
"title": "登录预警平台",
"subtitle": "使用公司账号进入预警平台",
"eyebrow": "WATCHMAN · EARLY WARNING",
"eyebrow": "预警平台 · EARLY WARNING",
"hero": "让异常{em}被看见{/em}",
"heroEm": "被看见",
"heroBefore": "让异常",
@@ -21,7 +21,7 @@
"unavailable": "登录服务暂不可用,请稍后再试",
"logout": "退出",
"forbiddenTitle": "没有访问权限",
"forbiddenBody": "当前账号已登录,但没有 Watchman 的查看、处理或管理角色。",
"forbiddenBody": "当前账号已登录,但没有预警平台的查看、处理或管理角色。",
"fixture": "本地身份模式,不能当作正式登录"
},
"shell": {
@@ -37,8 +37,10 @@
"nav": {
"home": "概览",
"datasources": "数据源",
"queries": "查询",
"create": "新建",
"detail": "详情"
"detail": "详情",
"version": "版本 v{no}"
},
"datasource": {
"list": {
@@ -46,7 +48,15 @@
"loading": "数据源加载中",
"loadFailed": "数据源加载失败",
"empty": "还没有数据源",
"emptyHint": "管理者可以新建第一个数据源。"
"emptyHint": "管理者可以新建第一个数据源。",
"filterName": "名称(模糊)",
"filterEngine": "引擎",
"filterStatus": "状态",
"filterSearch": "查询",
"filterReset": "重置",
"filterClear": "清除筛选",
"filterEmpty": "没有符合条件的数据源",
"filterEmptyHint": "试试改名称、引擎或状态,或点重置。"
},
"columns": {
"name": "名称",
@@ -167,5 +177,281 @@
},
"saved": "已保存",
"disabled": "已停用"
},
"query": {
"list": {
"create": "新建",
"loadFailed": "查询加载失败",
"empty": "还没有查询",
"emptyHint": "管理者可以新建第一个查询定义:选择数据源,写参数化 SQL,声明参数与输出契约。",
"filterName": "名称(模糊)",
"filterDatasource": "数据源",
"filterStatus": "状态",
"filterSearch": "查询",
"filterReset": "重置",
"filterClear": "清除筛选",
"filterEmpty": "没有符合条件的查询",
"filterEmptyHint": "试试改名称、数据源或状态,或点重置。"
},
"columns": {
"name": "名称",
"datasource": "数据源",
"status": "状态",
"latestVersion": "最新版本",
"currentVersion": "当前版本",
"updatedAt": "更新时间",
"actions": "操作"
},
"status": {
"enabled": "启用",
"disabled": "已停用"
},
"actions": {
"open": "打开",
"preview": "预览",
"previewDisabledWhy": "已停用,不能预览",
"backToList": "返回列表",
"backToDraft": "返回查询",
"backToQuery": "返回查询",
"save": "保存",
"publish": "发布",
"activate": "激活此版本",
"switchVersion": "切换版本",
"needSave": "请先保存",
"disable": "停用",
"enable": "启用",
"runPreview": "试跑预览",
"previewNeedSave": "请先保存,预览使用已保存的当前版本",
"add": "添加",
"remove": "删除"
},
"denied": {
"title": "无法进入查询",
"body": "只有管理者可以进入查询界面。"
},
"form": {
"basic": "基本信息",
"subNew": "新建",
"subSaved": "当前生效 {version}",
"name": "名称",
"namePlaceholder": "租户内唯一",
"nameTooLong": "名称最多 128 个字符",
"datasource": "数据源",
"datasourcePlaceholder": "请选择数据源",
"datasourceOff": "(已停用)",
"datasourcesFailed": "数据源列表加载失败",
"description": "用途说明",
"status": "状态",
"statusNew": "新建后默认启用",
"statusHint": "通过页脚「{action}」切换",
"sql": "SQL 模板",
"sqlPlaceholder": "SELECT lot_no FROM process_readings WHERE line_code = :line_code",
"sqlHint": "使用命名参数,例如 :line_code,值一律参数绑定,不拼接进 SQL。是否只读由数据源账户与执行器保证。",
"paramsTitle": "参数 schema",
"paramsHint": "SQL 中的 :name 必须在此声明,未声明的参数在试跑和保存时会被拒绝。",
"outputsTitle": "输出 schema",
"outputsHint": "输出契约,用于检查结果类型;只有名称和类型。",
"identifiersTitle": "允许的标识符",
"identifiersHint": "表或字段名不能当作参数值;只有这里声明的名称才允许出现在模板的 {example} 位置,留空表示不允许。",
"limits": "执行限制",
"limitsHint": "服务端有上限:timeout_ms 不超过 {timeout},max_rows 不超过 {rows}。",
"required": "必填",
"invalidRange": "须为 {min}–{max} 的整数"
},
"sqlParams": {
"none": "SQL 中尚未使用 :参数。",
"used": "SQL 中的参数:",
"undeclared": ":{name} 未声明",
"undeclaredTitle": "未在参数 schema 中声明,试跑和保存会被拒绝",
"unused": "{name} 未使用",
"unusedTitle": "已声明但 SQL 中未使用"
},
"params": {
"name": "参数名",
"type": "类型",
"required": "必填",
"default": "默认值",
"yes": "是",
"no": "否",
"add": "添加参数",
"empty": "尚未声明参数。",
"namePlaceholder": "例如 line_code",
"defaultPlaceholder": "可空",
"invalidName": "参数名不合法:{name}",
"duplicate": "参数名重复:{name}",
"invalidDefault": "默认值与类型不符:{name}"
},
"outputs": {
"name": "字段名",
"type": "类型",
"add": "添加输出字段",
"empty": "尚未声明输出字段。",
"namePlaceholder": "例如 lot_no",
"invalidName": "输出字段名不合法:{name}",
"duplicate": "输出字段名重复:{name}",
"invalidDefault": "输出字段不合法:{name}"
},
"identifiers": {
"none": "无(不允许动态标识符)",
"placeholder": "输入标识符后按回车,例如 process_readings",
"invalid": "标识符只能包含字母、数字和下划线,且不能以数字开头:{name}"
},
"preview": {
"title": "试跑预览",
"target": "预览对象:",
"targetVersion": "版本 v{no}(已冻结)",
"dirtyNote": "当前有未保存修改;请先保存再试跑(预览使用已保存的当前版本)。",
"needSaveNote": "保存后才能试跑预览。",
"noParams": "该查询没有声明参数,可直接试跑。",
"invalidValue": "值与参数类型不符",
"unset": "(未填)",
"none": "尚未试跑。填写参数后点击页脚「试跑预览」。",
"running": "试跑中",
"success": {
"title": "试跑成功",
"body": "返回 {count} 行样例,列符合输出契约。标记「脱敏」的列已被遮盖。"
},
"empty": {
"title": "空结果",
"body": "查询已成功执行,但没有符合条件的行。这不是失败,也不是类型错误。"
},
"illegal": {
"title": "输出类型不匹配",
"body": "查询已执行,但返回值与输出契约不符,整批结果不视为合法输出。",
"row": "行",
"field": "字段",
"expected": "契约类型",
"actual": "实际类型"
},
"failure": {
"timeout": {
"title": "执行超时",
"body": "超过 timeout_ms 仍未返回,已中止查询。可缩小时间窗或调整限制后重试。"
},
"unreachable": {
"title": "连接失败",
"body": "无法连接到数据源。请检查数据源与网络。"
},
"auth_failed": {
"title": "数据源认证失败",
"body": "数据源不接受已保存的账号或口令。请到数据源页面更新。"
},
"rejected": {
"title": "数据源拒绝连接",
"body": "数据源已响应但拒绝了连接,例如库名不存在。"
},
"sql_error": {
"title": "SQL 执行失败",
"body": "源库拒绝了该 SQL。请检查 SQL 模板。"
},
"limit_exceeded": {
"title": "超出 max_rows",
"body": "返回行数超过 max_rows={max_rows},整批结果未返回。请缩小条件或调大 max_rows。"
},
"validation": {
"title": "模板或参数无效",
"body": "查询模板或参数未通过校验,未向源库发起查询。"
},
"engine_readonly_unsupported": {
"title": "该引擎暂不支持试跑",
"body": "SQL Server 尚无服务端强制只读会话,本轮不执行其查询预览。请改用 PostgreSQL 或 MySQL 数据源;连接测试仍可用。"
},
"unknown": {
"title": "试跑失败",
"body": "查询没有完成。"
},
"noteCircuit": "连接类失败会计入该数据源的熔断统计。",
"noteNoCircuit": "该类失败不计入熔断统计。"
},
"disabled": {
"title": "已停用,未执行",
"queryBody": "该查询已停用,不能试跑。请先在页脚「启用」。",
"sourceBody": "所绑定的数据源已停用,不能试跑。"
},
"circuit": {
"title": "数据源熔断中,未执行",
"body": "数据源当前熔断,不会向源库发起查询。预计 {until} 后恢复。"
},
"masked": "脱敏",
"datasource": "数据源 {name}",
"onlyPreview": "仅预览:不创建报警、不发送通知、不进入正式运行。",
"failedUnknown": "试跑未完成,请稍后再试",
"targetCurrent": "当前版本(已保存内容)"
},
"versions": {
"title": "版本",
"hint": "保存会生成新版本并自动生效;可激活任一历史版本为当前。",
"empty": "尚无版本。",
"emptyCreate": "保存后会生成 v1,并出现在这里。",
"version": "版本",
"latest": "最新",
"current": "当前生效",
"publishedAt": "生成时间",
"publishedBy": "操作人",
"unpublished": "无版本",
"none": "无",
"loadFailed": "版本列表加载失败",
"frozenNote": "版本 {version} 已冻结,内容不可修改。更正请返回查询修改后保存为新版本;这里仍可试跑预览或激活。",
"info": "版本信息",
"readonly": "只读",
"query": "查询",
"activated": "已切换为 {version}",
"switchTitle": "切换版本 · {name}"
},
"refs": {
"title": "引用",
"empty": "尚无引用",
"loadFailed": "引用加载失败"
},
"publishConfirm": {
"title": "确认发布 {version}?",
"body": "将把当前已保存的草稿固化为不可变版本 {version}。发布后不能修改或删除,更正需发布新版本。",
"ok": "确认发布",
"cancel": "取消"
},
"disableConfirm": {
"title": "停用查询",
"body": "停用后不能试跑预览,记录与已发布版本仍然保留。确定停用「{name}」吗?",
"ok": "停用",
"cancel": "取消"
},
"disabledNote": "该查询已停用。仍可查看与编辑,但不能试跑预览;可在页脚「启用」。",
"notFound": "查询不存在",
"versionNotFound": "版本不存在",
"loadFailed": "查询加载失败",
"saveFailed": "操作未完成,请稍后再试",
"saved": "已保存",
"savedVersion": "已保存为 {version} 并设为当前",
"publishNeedSave": "有未保存修改,请先保存",
"published": "已保存 {version}",
"enabledDone": "已启用",
"disabledDone": "已停用",
"errors": {
"duplicate_name": "名称已存在,请换一个名称",
"datasource_not_found": "所选数据源不存在",
"datasource_not_database": "只能选择数据库类型的数据源",
"template_empty": "SQL 模板不能为空",
"param_schema_invalid": "参数 schema 不合法",
"param_default_invalid": "参数默认值与类型不符",
"output_schema_invalid": "输出 schema 不合法",
"allowed_identifiers_invalid": "允许的标识符不合法",
"limit_invalid": "执行限制须为不小于 1 的整数",
"disabled": "查询已停用,不能试跑",
"version_conflict": "版本号冲突,请刷新后重试",
"not_found": "记录不存在",
"version_immutable": "已发布版本不可修改",
"identifier_invalid": "模板中的标识符写法不合法",
"identifier_not_allowed": "模板用到了未声明允许的标识符",
"identifier_unterminated": "模板中的标识符没有结束",
"missing_param": "缺少必填参数",
"multiple_statements": "模板只能包含一条语句",
"param_type_mismatch": "参数值与类型不符",
"params_invalid": "参数格式不合法",
"template_unterminated": "模板中有未闭合的引号或注释",
"undeclared_param": "模板用到了未声明的参数",
"unknown_param": "传入了未声明的参数",
"unsupported_engine": "该数据源引擎暂不支持",
"unsupported_datasource": "该数据源类型暂不支持"
}
}
}
+292 -6
View File
@@ -1,9 +1,9 @@
{
"appName": "Watchman",
"appName": "預警平台",
"login": {
"title": "登入 Watchman",
"title": "登入預警平台",
"subtitle": "使用公司帳號進入預警平台",
"eyebrow": "WATCHMAN · EARLY WARNING",
"eyebrow": "預警平台 · EARLY WARNING",
"heroEm": "被看見",
"heroBefore": "讓異常",
"submitting": "登入中",
@@ -20,7 +20,7 @@
"unavailable": "登入服務暫不可用,請稍後再試",
"logout": "登出",
"forbiddenTitle": "沒有存取權限",
"forbiddenBody": "目前帳號已登入,但沒有 Watchman 的查看、處理或管理角色。",
"forbiddenBody": "目前帳號已登入,但沒有預警平台的查看、處理或管理角色。",
"fixture": "本地身分模式,不能當作正式登入"
},
"shell": {
@@ -36,8 +36,10 @@
"nav": {
"home": "概覽",
"datasources": "資料來源",
"queries": "查詢",
"create": "新增",
"detail": "詳情"
"detail": "詳情",
"version": "版本 v{no}"
},
"datasource": {
"list": {
@@ -45,7 +47,15 @@
"loading": "資料來源載入中",
"loadFailed": "資料來源載入失敗",
"empty": "還沒有資料來源",
"emptyHint": "管理者可以新增第一個資料來源。"
"emptyHint": "管理者可以新增第一個資料來源。",
"filterName": "名稱(模糊)",
"filterEngine": "引擎",
"filterStatus": "狀態",
"filterSearch": "查詢",
"filterReset": "重置",
"filterClear": "清除篩選",
"filterEmpty": "沒有符合條件的資料來源",
"filterEmptyHint": "試試改名稱、引擎或狀態,或點重置。"
},
"columns": {
"name": "名稱",
@@ -166,5 +176,281 @@
},
"saved": "已儲存",
"disabled": "已停用"
},
"query": {
"list": {
"create": "新建",
"loadFailed": "查詢載入失敗",
"empty": "還沒有查詢",
"emptyHint": "管理者可以新建第一個查詢定義:選擇資料來源,撰寫參數化 SQL,宣告參數與輸出契約。",
"filterName": "名稱(模糊)",
"filterDatasource": "資料來源",
"filterStatus": "狀態",
"filterSearch": "查詢",
"filterReset": "重置",
"filterClear": "清除篩選",
"filterEmpty": "沒有符合條件的查詢",
"filterEmptyHint": "試試改名稱、資料來源或狀態,或點重置。"
},
"columns": {
"name": "名稱",
"datasource": "資料來源",
"status": "狀態",
"latestVersion": "最新版本",
"currentVersion": "目前版本",
"updatedAt": "更新時間",
"actions": "操作"
},
"status": {
"enabled": "啟用",
"disabled": "已停用"
},
"actions": {
"open": "開啟",
"preview": "預覽",
"previewDisabledWhy": "已停用,不能預覽",
"backToList": "返回列表",
"backToDraft": "返回查詢",
"backToQuery": "返回查詢",
"save": "儲存",
"publish": "發布",
"activate": "啟用此版本",
"switchVersion": "切換版本",
"needSave": "請先儲存草稿",
"disable": "停用",
"enable": "啟用",
"runPreview": "試跑預覽",
"previewNeedSave": "請先儲存,預覽使用已儲存的目前版本",
"add": "新增",
"remove": "刪除"
},
"denied": {
"title": "無法進入查詢",
"body": "只有管理者可以進入查詢介面。"
},
"form": {
"basic": "基本資訊",
"subNew": "新建",
"subSaved": "目前生效 {version}",
"name": "名稱",
"namePlaceholder": "租戶內唯一",
"nameTooLong": "名稱最多 128 個字元",
"datasource": "資料來源",
"datasourcePlaceholder": "請選擇資料來源",
"datasourceOff": "(已停用)",
"datasourcesFailed": "資料來源列表載入失敗",
"description": "用途說明",
"status": "狀態",
"statusNew": "新建後預設啟用",
"statusHint": "透過頁尾「{action}」切換",
"sql": "SQL 範本",
"sqlPlaceholder": "SELECT lot_no FROM process_readings WHERE line_code = :line_code",
"sqlHint": "使用具名參數,例如 :line_code,值一律參數綁定,不拼接進 SQL。是否唯讀由資料來源帳戶與執行器保證。",
"paramsTitle": "參數 schema",
"paramsHint": "SQL 中的 :name 必須在此宣告,未宣告的參數在試跑和發布時會被拒絕。",
"outputsTitle": "輸出 schema",
"outputsHint": "輸出契約,用於檢查結果型別;只有名稱和型別。",
"identifiersTitle": "允許的識別字",
"identifiersHint": "表或欄位名不能當作參數值;只有這裡宣告的名稱才允許出現在範本的 {example} 位置,留空表示不允許。",
"limits": "執行限制",
"limitsHint": "伺服端有上限:timeout_ms 不超過 {timeout},max_rows 不超過 {rows}。",
"required": "必填",
"invalidRange": "須為 {min}–{max} 的整數"
},
"sqlParams": {
"none": "SQL 中尚未使用 :參數。",
"used": "SQL 中的參數:",
"undeclared": ":{name} 未宣告",
"undeclaredTitle": "未在參數 schema 中宣告,試跑和儲存會被拒絕",
"unused": "{name} 未使用",
"unusedTitle": "已宣告但 SQL 中未使用"
},
"params": {
"name": "參數名",
"type": "型別",
"required": "必填",
"default": "預設值",
"yes": "是",
"no": "否",
"add": "新增參數",
"empty": "尚未宣告參數。",
"namePlaceholder": "例如 line_code",
"defaultPlaceholder": "可空",
"invalidName": "參數名不合法:{name}",
"duplicate": "參數名重複:{name}",
"invalidDefault": "預設值與型別不符:{name}"
},
"outputs": {
"name": "欄位名",
"type": "型別",
"add": "新增輸出欄位",
"empty": "尚未宣告輸出欄位。",
"namePlaceholder": "例如 lot_no",
"invalidName": "輸出欄位名不合法:{name}",
"duplicate": "輸出欄位名重複:{name}",
"invalidDefault": "輸出欄位不合法:{name}"
},
"identifiers": {
"none": "無(不允許動態識別字)",
"placeholder": "輸入識別字後按 Enter,例如 process_readings",
"invalid": "識別字只能包含英文字母、數字和底線,且不能以數字開頭:{name}"
},
"preview": {
"title": "試跑預覽",
"target": "預覽對象:",
"targetVersion": "版本 v{no}(已凍結)",
"dirtyNote": "目前有未儲存修改;請先儲存再試跑(預覽使用已儲存的目前版本)。",
"needSaveNote": "儲存後才能試跑預覽。",
"noParams": "該查詢沒有宣告參數,可直接試跑。",
"invalidValue": "值與參數型別不符",
"unset": "(未填)",
"none": "尚未試跑。填寫參數後點擊頁尾「試跑預覽」。",
"running": "試跑中",
"success": {
"title": "試跑成功",
"body": "回傳 {count} 列樣本,欄位符合輸出契約。標記「遮罩」的欄位已被遮蓋。"
},
"empty": {
"title": "空結果",
"body": "查詢已成功執行,但沒有符合條件的列。這不是失敗,也不是型別錯誤。"
},
"illegal": {
"title": "輸出型別不符",
"body": "查詢已執行,但回傳值與輸出契約不符,整批結果不視為合法輸出。",
"row": "列",
"field": "欄位",
"expected": "契約型別",
"actual": "實際型別"
},
"failure": {
"timeout": {
"title": "執行逾時",
"body": "超過 timeout_ms 仍未回應,已中止查詢。可縮小時間窗或調整限制後重試。"
},
"unreachable": {
"title": "連線失敗",
"body": "無法連線到資料來源。請檢查資料來源與網路。"
},
"auth_failed": {
"title": "資料來源認證失敗",
"body": "資料來源不接受已儲存的帳號或密碼。請到資料來源頁面更新。"
},
"rejected": {
"title": "資料來源拒絕連線",
"body": "資料來源已回應但拒絕了連線,例如資料庫名稱不存在。"
},
"sql_error": {
"title": "SQL 執行失敗",
"body": "來源資料庫拒絕了該 SQL。請檢查 SQL 範本。"
},
"limit_exceeded": {
"title": "超出 max_rows",
"body": "回傳列數超過 max_rows={max_rows},整批結果未回傳。請縮小條件或調大 max_rows。"
},
"validation": {
"title": "範本或參數無效",
"body": "查詢範本或參數未通過驗證,未向來源資料庫發起查詢。"
},
"engine_readonly_unsupported": {
"title": "此引擎暫不支援試跑",
"body": "SQL Server 尚無服務端強制唯讀工作階段,本輪不執行其查詢預覽。請改用 PostgreSQL 或 MySQL 資料來源;連線測試仍可用。"
},
"unknown": {
"title": "試跑失敗",
"body": "查詢沒有完成。"
},
"noteCircuit": "連線類失敗會計入該資料來源的熔斷統計。",
"noteNoCircuit": "此類失敗不計入熔斷統計。"
},
"disabled": {
"title": "已停用,未執行",
"queryBody": "該查詢已停用,不能試跑。請先在頁尾「啟用」。",
"sourceBody": "所綁定的資料來源已停用,不能試跑。"
},
"circuit": {
"title": "資料來源熔斷中,未執行",
"body": "資料來源目前熔斷,不會向來源資料庫發起查詢。預計 {until} 後恢復。"
},
"masked": "遮罩",
"datasource": "資料來源 {name}",
"onlyPreview": "僅預覽:不建立警報、不發送通知、不進入正式運行。",
"failedUnknown": "試跑未完成,請稍後再試",
"targetCurrent": "目前版本(已儲存內容)"
},
"versions": {
"title": "版本",
"hint": "儲存會產生新版本並自動生效;可啟用任一歷史版本為目前。",
"empty": "尚無版本。",
"emptyCreate": "儲存後會產生 v1,並出現在這裡。",
"version": "版本",
"latest": "最新",
"current": "目前生效",
"publishedAt": "產生時間",
"publishedBy": "操作人",
"unpublished": "無版本",
"none": "無",
"loadFailed": "版本列表載入失敗",
"frozenNote": "版本 {version} 已凍結,內容不可修改。更正請返回查詢修改後儲存為新版本;這裡仍可試跑預覽或啟用。",
"info": "版本資訊",
"readonly": "唯讀",
"query": "查詢",
"activated": "已切換為 {version}",
"switchTitle": "切換版本 · {name}"
},
"refs": {
"title": "引用",
"empty": "尚無引用",
"loadFailed": "引用載入失敗"
},
"publishConfirm": {
"title": "確認發布 {version}?",
"body": "將把目前已儲存的草稿固化為不可變版本 {version}。發布後不能修改或刪除,更正需發布新版本。",
"ok": "確認發布",
"cancel": "取消"
},
"disableConfirm": {
"title": "停用查詢",
"body": "停用後不能試跑預覽,記錄與已發布版本仍然保留。確定停用「{name}」嗎?",
"ok": "停用",
"cancel": "取消"
},
"disabledNote": "該查詢已停用。仍可檢視與編輯草稿,但不能試跑預覽;可在頁尾「啟用」。",
"notFound": "查詢不存在",
"versionNotFound": "版本不存在",
"loadFailed": "查詢載入失敗",
"saveFailed": "操作未完成,請稍後再試",
"saved": "草稿已儲存",
"savedVersion": "已儲存為 {version} 並設為目前",
"publishNeedSave": "有未儲存修改,請先儲存",
"published": "已儲存 {version}",
"enabledDone": "已啟用",
"disabledDone": "已停用",
"errors": {
"duplicate_name": "名稱已存在,請換一個名稱",
"datasource_not_found": "所選資料來源不存在",
"datasource_not_database": "只能選擇資料庫類型的資料來源",
"template_empty": "SQL 範本不能為空",
"param_schema_invalid": "參數 schema 不合法",
"param_default_invalid": "參數預設值與型別不符",
"output_schema_invalid": "輸出 schema 不合法",
"allowed_identifiers_invalid": "允許的識別字不合法",
"limit_invalid": "執行限制須為不小於 1 的整數",
"disabled": "查詢已停用,不能試跑",
"version_conflict": "版本號衝突,請重新整理後重試",
"not_found": "記錄不存在",
"version_immutable": "已發布版本不可修改",
"identifier_invalid": "範本中的識別字寫法不合法",
"identifier_not_allowed": "範本用到了未宣告允許的識別字",
"identifier_unterminated": "範本中的識別字沒有結束",
"missing_param": "缺少必填參數",
"multiple_statements": "範本只能包含一條語句",
"param_type_mismatch": "參數值與型別不符",
"params_invalid": "參數格式不合法",
"template_unterminated": "範本中有未閉合的引號或註解",
"undeclared_param": "範本用到了未宣告的參數",
"unknown_param": "傳入了未宣告的參數",
"unsupported_engine": "該資料來源引擎暫不支援",
"unsupported_datasource": "該資料來源類型暫不支援"
}
}
}
+51 -15
View File
@@ -1,13 +1,14 @@
<script setup lang="ts">
/**
* Signed-in layout: side navigation, a top bar with the breadcrumb, and the routed page.
* The routed page owns its own scrolling, so footers can stay outside the scroll area.
* Signed-in layout: side navigation with brand + user footer, a top breadcrumb bar, and
* the routed page. The routed page owns its own scrolling so footers can stay outside it.
*/
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { RouterLink, RouterView, useRoute } from "vue-router";
import { ElBreadcrumb, ElBreadcrumbItem, ElButton } from "element-plus";
import { allowsDatasources } from "./session";
import logoUrl from "./assets/logo.jpg";
import { allowsDatasources, allowsQueries } from "./session";
import { useAuthStore } from "./stores/auth";
defineProps<{ displayName?: string }>();
@@ -17,21 +18,38 @@ const { t } = useI18n();
const route = useRoute();
const auth = useAuthStore();
const CRUMB_LINKS: Record<string, string> = { datasources: "/datasources" };
const CRUMB_LINKS: Record<string, string> = { datasources: "/datasources", queries: "/queries" };
/** Where a non-final crumb goes. A query's "detail" crumb is the draft page of the same query. */
function crumbLink(key: string): string | undefined {
if (key === "detail" && route.name === "query-version" && route.params.id) {
return `/queries/${encodeURIComponent(String(route.params.id))}`;
}
return CRUMB_LINKS[key];
}
function crumbLabel(key: string): string {
return key === "version"
? t("nav.version", { no: String(route.params.versionNo ?? "") })
: t(`nav.${key}`);
}
const crumbs = computed(() => {
let keys = (route.meta.crumbs as string[] | undefined) ?? [];
// Roles that cannot enter datasources see the list level only.
// Roles that cannot enter datasources or queries see the list level only.
if (route.path.startsWith("/datasources") && !allowsDatasources(auth.user?.roles ?? [])) {
keys = ["datasources"];
}
if (route.path.startsWith("/queries") && !allowsQueries(auth.user?.roles ?? [])) {
keys = ["queries"];
}
const items: { label: string; to?: string }[] = [
{ label: t("appName"), to: keys.length > 0 ? "/" : undefined },
];
keys.forEach((key, index) => {
items.push({
label: t(`nav.${key}`),
to: index < keys.length - 1 ? CRUMB_LINKS[key] : undefined,
label: crumbLabel(key),
to: index < keys.length - 1 ? crumbLink(key) : undefined,
});
});
return items;
@@ -47,11 +65,14 @@ const activeClass = "!bg-[#eef0fb] !font-semibold !text-[var(--color-primary)]";
class="flex h-screen bg-[var(--bg-surface-soft)] text-[length:var(--font-size-base)] text-[var(--text-primary)]"
>
<aside
class="w-48 shrink-0 border-r border-[var(--border-subtle)] bg-white px-2.5 py-3.5"
class="flex w-48 shrink-0 flex-col border-r border-[var(--border-subtle)] bg-white px-2.5 py-3.5"
data-testid="side-nav"
>
<div class="px-2.5 pb-3.5 text-base font-bold tracking-wide">{{ t("appName") }}</div>
<nav class="flex flex-col gap-1">
<div class="mb-3.5 flex items-center gap-2 px-2.5" data-testid="side-brand">
<img :src="logoUrl" alt="" class="h-7 w-7 shrink-0 object-contain" data-testid="side-logo" />
<span class="text-base font-bold tracking-wide">{{ t("appName") }}</span>
</div>
<nav class="flex flex-1 flex-col gap-1">
<RouterLink to="/" :class="linkClass" :exact-active-class="activeClass" data-testid="nav-home">
{{ t("nav.home") }}
</RouterLink>
@@ -63,21 +84,36 @@ const activeClass = "!bg-[#eef0fb] !font-semibold !text-[var(--color-primary)]";
>
{{ t("nav.datasources") }}
</RouterLink>
<RouterLink
to="/queries"
:class="linkClass"
:active-class="activeClass"
data-testid="nav-queries"
>
{{ t("nav.queries") }}
</RouterLink>
</nav>
<div
class="mt-3 border-t border-[var(--border-subtle)] px-2.5 pt-3"
data-testid="side-user"
>
<div class="mb-2 text-[13px] text-[var(--text-secondary)]" data-testid="shell-welcome">
{{ t("shell.welcome", { name: displayName }) }}
</div>
<ElButton class="w-full" data-testid="logout" @click="emit('logout')">
{{ t("login.logout") }}
</ElButton>
</div>
</aside>
<div class="flex min-w-0 flex-1 flex-col">
<header
class="flex h-12 shrink-0 items-center justify-between border-b border-[var(--border-subtle)] bg-white px-5"
class="flex h-12 shrink-0 items-center border-b border-[var(--border-subtle)] bg-white px-5"
>
<ElBreadcrumb separator="/" data-testid="breadcrumb">
<ElBreadcrumbItem v-for="item in crumbs" :key="item.label" :to="item.to">
{{ item.label }}
</ElBreadcrumbItem>
</ElBreadcrumb>
<div class="flex items-center gap-3">
<span data-testid="shell-welcome">{{ t("shell.welcome", { name: displayName }) }}</span>
<ElButton data-testid="logout" @click="emit('logout')">{{ t("login.logout") }}</ElButton>
</div>
</header>
<main class="min-h-0 flex-1 overflow-hidden">
<RouterView />
@@ -1,21 +1,26 @@
<script setup lang="ts">
/**
* Datasource list. The page button sits above the table, right aligned.
* Row actions stay in the row. Disabled rows stay visible, can be enabled again and cannot be
* tested; rows with an open circuit cannot be tested until the cooldown ends.
* Datasource list. Filters are drafts until 查询; sort and page hit the server. Row actions
* stay in the row. Disabled rows stay visible, can be enabled again and cannot be tested;
* rows with an open circuit cannot be tested until the cooldown ends.
*/
import { onMounted, ref } from "vue";
import { computed, onMounted, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import {
ElAlert,
ElButton,
ElInput,
ElMessage,
ElMessageBox,
ElOption,
ElPagination,
ElSelect,
ElTable,
ElTableColumn,
vLoading,
} from "element-plus";
import { LIST_DEFAULT_PAGE_SIZE, LIST_PAGE_SIZES, actionsColumnWidth } from "../tableLayout";
import { disableDatasource, enableDatasource, listDatasources } from "./client";
import { describeError } from "./errors";
import { engineLabel, formatDateTime } from "./format";
@@ -25,22 +30,103 @@ const { t, te } = useI18n();
const router = useRouter();
const items = ref<Datasource[]>([]);
const total = ref(0);
const loading = ref(true);
const loadError = ref("");
const draft = reactive({ name: "", engine: "", status: "" });
const applied = reactive({ name: "", engine: "", status: "" });
const page = ref(1);
const pageSize = ref(LIST_DEFAULT_PAGE_SIZE);
const sortBy = ref("created_at");
const sortOrder = ref<"asc" | "desc">("asc");
const hasAppliedFilters = computed(
() => applied.name.trim() !== "" || applied.engine !== "" || applied.status !== "",
);
/** Three row actions: edit / test / enable|disable. */
const actionsWidth = actionsColumnWidth(3);
async function load(): Promise<void> {
loading.value = true;
loadError.value = "";
try {
items.value = (await listDatasources()).items;
const enabled =
applied.status === "enabled" ? true : applied.status === "disabled" ? false : undefined;
const result = await listDatasources({
name: applied.name.trim() || undefined,
engine: applied.engine || undefined,
enabled,
sort_by: sortBy.value,
sort_order: sortOrder.value,
page: page.value,
page_size: pageSize.value,
});
items.value = result.items;
total.value = result.total;
} catch (error) {
loadError.value = describeError(error, t, te, "datasource.list.loadFailed");
items.value = [];
total.value = 0;
} finally {
loading.value = false;
}
}
// Table slots type their rows loosely, so row handlers take the slot row and narrow it here.
function applyFilters(): void {
applied.name = draft.name;
applied.engine = draft.engine;
applied.status = draft.status;
page.value = 1;
void load();
}
function resetFilters(): void {
draft.name = "";
draft.engine = "";
draft.status = "";
applied.name = "";
applied.engine = "";
applied.status = "";
page.value = 1;
void load();
}
function onSortChange(payload: { prop: string | null; order: string | null }): void {
const propMap: Record<string, string> = {
name: "name",
engine: "engine",
host: "host",
port: "port",
database_name: "database_name",
username: "username",
status: "enabled",
last_test_at: "last_test_at",
};
const next = payload.prop ? propMap[payload.prop] : undefined;
if (!next || !payload.order) {
sortBy.value = "created_at";
sortOrder.value = "asc";
} else {
sortBy.value = next;
sortOrder.value = payload.order === "ascending" ? "asc" : "desc";
}
page.value = 1;
void load();
}
function onPageChange(next: number): void {
page.value = next;
void load();
}
function onSizeChange(next: number): void {
pageSize.value = next;
page.value = 1;
void load();
}
function asRow(source: unknown): Datasource {
return source as Datasource;
}
@@ -133,10 +219,44 @@ onMounted(load);
<template>
<div class="h-full overflow-auto p-5" data-testid="datasource-list">
<div class="mb-3 flex justify-end">
<ElButton type="primary" data-testid="datasource-create" @click="openCreate">
{{ t("datasource.list.create") }}
<div class="mb-3 flex flex-wrap items-center gap-2" data-testid="datasource-list-toolbar">
<div class="w-[200px]" data-testid="datasource-filter-name">
<ElInput v-model="draft.name" clearable :placeholder="t('datasource.list.filterName')" />
</div>
<div class="w-[160px]" data-testid="datasource-filter-engine">
<ElSelect
v-model="draft.engine"
clearable
class="w-full"
:placeholder="t('datasource.list.filterEngine')"
>
<ElOption label="PostgreSQL" value="postgresql" />
<ElOption label="MySQL" value="mysql" />
<ElOption label="SQL Server" value="sqlserver" />
</ElSelect>
</div>
<div class="w-[140px]" data-testid="datasource-filter-status">
<ElSelect
v-model="draft.status"
clearable
class="w-full"
:placeholder="t('datasource.list.filterStatus')"
>
<ElOption :label="t('datasource.status.enabled')" value="enabled" />
<ElOption :label="t('datasource.status.disabled')" value="disabled" />
</ElSelect>
</div>
<ElButton type="primary" data-testid="datasource-filter-search" @click="applyFilters">
{{ t("datasource.list.filterSearch") }}
</ElButton>
<ElButton data-testid="datasource-filter-reset" @click="resetFilters">
{{ t("datasource.list.filterReset") }}
</ElButton>
<div class="ml-auto">
<ElButton type="primary" data-testid="datasource-create" @click="openCreate">
{{ t("datasource.list.create") }}
</ElButton>
</div>
</div>
<ElAlert
@@ -148,83 +268,136 @@ onMounted(load);
:closable="false"
/>
<div
v-else-if="!loading && items.length === 0"
v-else-if="!loading && total === 0 && !hasAppliedFilters"
data-testid="datasource-empty"
class="rounded-lg border border-dashed border-[var(--border-default)] bg-white px-5 py-14 text-center"
>
<h3 class="mb-1.5 text-[15px] font-semibold">{{ t("datasource.list.empty") }}</h3>
<p class="text-[var(--text-secondary)]">{{ t("datasource.list.emptyHint") }}</p>
</div>
<ElTable
v-else
v-loading="loading"
:data="items"
data-testid="datasource-table"
:row-class-name="rowClass"
<div
v-else-if="!loading && total === 0 && hasAppliedFilters"
data-testid="datasource-filter-empty"
class="rounded-lg border border-dashed border-[var(--border-default)] bg-white px-5 py-14 text-center"
>
<ElTableColumn prop="name" :label="t('datasource.columns.name')" min-width="140" />
<ElTableColumn :label="t('datasource.columns.engine')" min-width="110">
<template #default="{ row }">{{ engineLabel(row.engine) }}</template>
</ElTableColumn>
<ElTableColumn prop="host" :label="t('datasource.columns.host')" min-width="170" />
<ElTableColumn prop="port" :label="t('datasource.columns.port')" width="80" />
<ElTableColumn prop="database_name" :label="t('datasource.columns.database')" min-width="130" />
<ElTableColumn prop="username" :label="t('datasource.columns.username')" min-width="130" />
<ElTableColumn :label="t('datasource.columns.status')" min-width="150">
<template #default="{ row }">
<span class="inline-flex items-center gap-1.5">
<span
class="h-[7px] w-[7px] rounded-full"
:class="row.enabled ? 'bg-[#1a7f37]' : 'bg-[var(--text-muted)]'"
/>
{{ row.enabled ? t("datasource.status.enabled") : t("datasource.status.disabled") }}
<span v-if="row.circuit_state === 'open'" class="text-xs text-[#cf222e]" data-testid="row-circuit-open">
{{ t("datasource.status.circuitOpen") }}
<h3 class="mb-1.5 text-[15px] font-semibold">{{ t("datasource.list.filterEmpty") }}</h3>
<p class="text-[var(--text-secondary)]">{{ t("datasource.list.filterEmptyHint") }}</p>
</div>
<template v-else>
<ElTable
v-loading="loading"
:data="items"
row-key="id"
data-testid="datasource-table"
:row-class-name="rowClass"
@sort-change="onSortChange"
>
<ElTableColumn prop="name" :label="t('datasource.columns.name')" min-width="140" sortable="custom" />
<ElTableColumn prop="engine" :label="t('datasource.columns.engine')" min-width="110" sortable="custom">
<template #default="{ row }">{{ engineLabel(row.engine) }}</template>
</ElTableColumn>
<ElTableColumn prop="host" :label="t('datasource.columns.host')" min-width="170" sortable="custom" />
<ElTableColumn prop="port" :label="t('datasource.columns.port')" width="90" sortable="custom" />
<ElTableColumn
prop="database_name"
:label="t('datasource.columns.database')"
min-width="130"
sortable="custom"
/>
<ElTableColumn
prop="username"
:label="t('datasource.columns.username')"
min-width="130"
sortable="custom"
/>
<ElTableColumn prop="status" :label="t('datasource.columns.status')" min-width="150" sortable="custom">
<template #default="{ row }">
<span class="inline-flex items-center gap-1.5">
<span
class="h-[7px] w-[7px] rounded-full"
:class="row.enabled ? 'bg-[#1a7f37]' : 'bg-[var(--text-muted)]'"
/>
{{ row.enabled ? t("datasource.status.enabled") : t("datasource.status.disabled") }}
<span
v-if="row.circuit_state === 'open'"
class="text-xs text-[#cf222e]"
data-testid="row-circuit-open"
>
{{ t("datasource.status.circuitOpen") }}
</span>
</span>
</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('datasource.columns.lastTest')" min-width="190">
<template #default="{ row }">
<span
:class="
row.last_test_category === 'success'
? 'text-[#1a7f37]'
: row.last_test_category
? 'text-[#cf222e]'
: 'text-[var(--text-muted)]'
"
>
{{ lastTestText(row) }}
</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('datasource.columns.actions')" width="148" fixed="right">
<template #default="{ row }">
<div class="whitespace-nowrap" :data-testid="`datasource-row-${row.id}`">
<ElButton link type="primary" data-testid="row-edit" @click="openDetail(row)">
{{ t("datasource.actions.edit") }}
</ElButton>
<ElButton
link
type="primary"
data-testid="row-test"
:disabled="testBlocked(row)"
:title="testTitle(row)"
@click="openTest(row)"
</template>
</ElTableColumn>
<ElTableColumn
prop="last_test_at"
:label="t('datasource.columns.lastTest')"
min-width="190"
sortable="custom"
>
<template #default="{ row }">
<span
:class="
row.last_test_category === 'success'
? 'text-[#1a7f37]'
: row.last_test_category
? 'text-[#cf222e]'
: 'text-[var(--text-muted)]'
"
>
{{ t("datasource.actions.test") }}
</ElButton>
<ElButton v-if="row.enabled" link type="danger" data-testid="row-disable" @click="disable(row)">
{{ t("datasource.actions.disable") }}
</ElButton>
<ElButton v-else link type="success" data-testid="row-enable" @click="enable(row)">
{{ t("datasource.actions.enable") }}
</ElButton>
</div>
</template>
</ElTableColumn>
</ElTable>
{{ lastTestText(row) }}
</span>
</template>
</ElTableColumn>
<ElTableColumn
:label="t('datasource.columns.actions')"
:width="actionsWidth"
align="right"
fixed="right"
>
<template #default="{ row }">
<div class="whitespace-nowrap" :data-testid="`datasource-row-${row.id}`">
<ElButton link type="primary" data-testid="row-edit" @click="openDetail(row)">
{{ t("datasource.actions.edit") }}
</ElButton>
<ElButton
link
type="primary"
data-testid="row-test"
:disabled="testBlocked(row)"
:title="testTitle(row)"
@click="openTest(row)"
>
{{ t("datasource.actions.test") }}
</ElButton>
<ElButton
v-if="row.enabled"
link
type="danger"
data-testid="row-disable"
@click="disable(row)"
>
{{ t("datasource.actions.disable") }}
</ElButton>
<ElButton v-else link type="success" data-testid="row-enable" @click="enable(row)">
{{ t("datasource.actions.enable") }}
</ElButton>
</div>
</template>
</ElTableColumn>
</ElTable>
<div class="mt-3 flex justify-end" data-testid="datasource-pagination">
<ElPagination
background
layout="total, sizes, prev, pager, next"
:total="total"
:page-size="pageSize"
:page-sizes="[...LIST_PAGE_SIZES]"
:current-page="page"
@current-change="onPageChange"
@size-change="onSizeChange"
/>
</div>
</template>
</div>
</template>
+20 -2
View File
@@ -6,14 +6,32 @@ import type {
ConnectionTestOutcome,
Datasource,
DatasourceList,
DatasourceListParams,
DatasourceReferences,
DraftTestOutcome,
} from "./types";
const JSON_HEADERS = { "Content-Type": "application/json" };
export function listDatasources(): Promise<DatasourceList> {
return api<DatasourceList>("/datasources");
function toQuery(params?: DatasourceListParams): string {
if (!params) {
return "";
}
const q = new URLSearchParams();
if (params.name) q.set("name", params.name);
if (params.engine) q.set("engine", params.engine);
if (params.enabled !== undefined) q.set("enabled", String(params.enabled));
if (params.sort_by) q.set("sort_by", params.sort_by);
if (params.sort_order) q.set("sort_order", params.sort_order);
if (params.page !== undefined) q.set("page", String(params.page));
if (params.page_size !== undefined) q.set("page_size", String(params.page_size));
if (params.usable) q.set("usable", "true");
const text = q.toString();
return text ? `?${text}` : "";
}
export function listDatasources(params?: DatasourceListParams): Promise<DatasourceList> {
return api<DatasourceList>(`/datasources${toQuery(params)}`);
}
export function getDatasource(id: string): Promise<Datasource> {
+18 -1
View File
@@ -48,7 +48,24 @@ export type Datasource = {
updated_at: string | null;
};
export type DatasourceList = { items: Datasource[] };
export type DatasourceList = {
items: Datasource[];
total: number;
page: number;
page_size: number;
};
/** Console list query params; omit fields the server should ignore. */
export type DatasourceListParams = {
name?: string;
engine?: string;
enabled?: boolean;
sort_by?: string;
sort_order?: "asc" | "desc";
page?: number;
page_size?: number;
usable?: boolean;
};
export type DatasourceReferences = { id: string; items: unknown[] };
@@ -0,0 +1,74 @@
<script setup lang="ts">
/**
* Allowed identifiers: closable tags plus an input (Enter or the add button). Only names the
* backend accepts are added. Readonly shows the frozen list without the input.
* Boundary: these names are the only ones allowed in the template's `{{name}}` identifier
* position; values still go through parameters.
*/
import { ref } from "vue";
import { useI18n } from "vue-i18n";
import { ElButton, ElInput, ElTag } from "element-plus";
import { isValidIdentifier } from "./validation";
const props = defineProps<{ modelValue: string[]; readonly?: boolean }>();
const emit = defineEmits<{ "update:modelValue": [items: string[]] }>();
const { t } = useI18n();
const input = ref("");
const problem = ref("");
function add(): void {
const value = input.value.trim();
problem.value = "";
if (value === "") {
return;
}
if (!isValidIdentifier(value)) {
problem.value = t("query.identifiers.invalid", { name: value });
return;
}
if (!props.modelValue.includes(value)) {
emit("update:modelValue", [...props.modelValue, value]);
}
input.value = "";
}
function remove(name: string): void {
emit(
"update:modelValue",
props.modelValue.filter((item) => item !== name),
);
}
</script>
<template>
<div data-testid="identifiers-block">
<div class="flex flex-wrap items-center gap-1.5" data-testid="identifier-tags">
<span v-if="modelValue.length === 0" class="text-[var(--text-muted)]">
{{ t("query.identifiers.none") }}
</span>
<ElTag
v-for="name in modelValue"
:key="name"
:closable="!readonly"
effect="plain"
data-testid="identifier-tag"
@close="remove(name)"
>
{{ name }}
</ElTag>
</div>
<div v-if="!readonly" class="mt-2.5 flex max-w-md gap-2">
<ElInput
v-model="input"
data-testid="identifier-input"
:placeholder="t('query.identifiers.placeholder')"
@keyup.enter="add"
/>
<ElButton data-testid="identifier-add" @click="add">{{ t("query.actions.add") }}</ElButton>
</div>
<p v-if="problem" class="mt-1.5 text-[var(--el-color-danger)]" data-testid="identifier-problem">
{{ problem }}
</p>
</div>
</template>
@@ -0,0 +1,77 @@
<script setup lang="ts">
/**
* Output schema table (the contract used to check result types): editable name and type rows
* for the draft, or plain text when `readonly` (a frozen version).
*/
import { useI18n } from "vue-i18n";
import { ElButton, ElInput, ElOption, ElSelect, ElTable, ElTableColumn } from "element-plus";
import { newOutputRow } from "./payload";
import { OUTPUT_TYPES, type OutputRow } from "./types";
const props = defineProps<{ modelValue: OutputRow[]; readonly?: boolean }>();
const emit = defineEmits<{ "update:modelValue": [rows: OutputRow[]] }>();
const { t } = useI18n();
function add(): void {
emit("update:modelValue", [...props.modelValue, newOutputRow()]);
}
function remove(key: number): void {
emit(
"update:modelValue",
props.modelValue.filter((row) => row.key !== key),
);
}
</script>
<template>
<div data-testid="outputs-block">
<div v-if="!readonly" class="mb-2 flex justify-end">
<ElButton data-testid="output-add" @click="add">{{ t("query.outputs.add") }}</ElButton>
</div>
<p
v-if="modelValue.length === 0"
data-testid="outputs-empty"
class="rounded-lg border border-dashed border-[var(--border-default)] px-5 py-4 text-center text-[var(--text-secondary)]"
>
{{ t("query.outputs.empty") }}
</p>
<ElTable v-else :data="modelValue" row-key="key" data-testid="outputs-table">
<ElTableColumn :label="t('query.outputs.name')" min-width="200">
<template #default="{ row }">
<ElInput
v-if="!readonly"
v-model="row.name"
class="query-mono"
data-testid="output-name"
:placeholder="t('query.outputs.namePlaceholder')"
/>
<span v-else class="query-mono">{{ row.name }}</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('query.outputs.type')" min-width="160">
<template #default="{ row }">
<ElSelect v-if="!readonly" v-model="row.type" class="w-full" data-testid="output-type">
<ElOption v-for="type in OUTPUT_TYPES" :key="type" :label="type" :value="type" />
</ElSelect>
<span v-else class="query-mono">{{ row.type }}</span>
</template>
</ElTableColumn>
<ElTableColumn v-if="!readonly" :label="t('query.columns.actions')" width="90" align="right">
<template #default="{ row }">
<ElButton link type="danger" data-testid="output-remove" @click="remove(row.key)">
{{ t("query.actions.remove") }}
</ElButton>
</template>
</ElTableColumn>
</ElTable>
</div>
</template>
<style scoped>
.query-mono,
.query-mono :deep(input) {
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
}
</style>
@@ -0,0 +1,108 @@
<script setup lang="ts">
/**
* Parameter schema table. Editable rows (name, type, required, default) for the draft, or
* plain text when `readonly` (a frozen version). Rows are removed in the row; adding sits
* above the table. The default is kept as text and converted by type when the body is built.
*/
import { useI18n } from "vue-i18n";
import { ElButton, ElCheckbox, ElInput, ElOption, ElSelect, ElTable, ElTableColumn } from "element-plus";
import { newParamRow } from "./payload";
import { VALUE_TYPES, type ParamRow } from "./types";
const props = defineProps<{ modelValue: ParamRow[]; readonly?: boolean }>();
const emit = defineEmits<{ "update:modelValue": [rows: ParamRow[]] }>();
const { t } = useI18n();
function add(): void {
emit("update:modelValue", [...props.modelValue, newParamRow()]);
}
function remove(key: number): void {
emit(
"update:modelValue",
props.modelValue.filter((row) => row.key !== key),
);
}
</script>
<template>
<div data-testid="params-block">
<div v-if="!readonly" class="mb-2 flex justify-end">
<ElButton data-testid="param-add" @click="add">{{ t("query.params.add") }}</ElButton>
</div>
<p
v-if="modelValue.length === 0"
data-testid="params-empty"
class="rounded-lg border border-dashed border-[var(--border-default)] px-5 py-4 text-center text-[var(--text-secondary)]"
>
{{ t("query.params.empty") }}
</p>
<ElTable v-else :data="modelValue" row-key="key" data-testid="params-table">
<ElTableColumn :label="t('query.params.name')" min-width="170">
<template #default="{ row }">
<ElInput
v-if="!readonly"
v-model="row.name"
class="query-mono"
data-testid="param-name"
:placeholder="t('query.params.namePlaceholder')"
/>
<span v-else class="query-mono">{{ row.name }}</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('query.params.type')" min-width="130">
<template #default="{ row }">
<ElSelect v-if="!readonly" v-model="row.type" class="w-full" data-testid="param-type">
<ElOption v-for="type in VALUE_TYPES" :key="type" :label="type" :value="type" />
</ElSelect>
<span v-else class="query-mono">{{ row.type }}</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('query.params.required')" width="90">
<template #default="{ row }">
<ElCheckbox v-if="!readonly" v-model="row.required" data-testid="param-required" />
<span v-else>{{ row.required ? t("query.params.yes") : t("query.params.no") }}</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('query.params.default')" min-width="170">
<template #default="{ row }">
<template v-if="!readonly">
<ElSelect
v-if="row.type === 'boolean'"
v-model="row.defaultText"
class="w-full"
clearable
data-testid="param-default"
:placeholder="t('query.params.defaultPlaceholder')"
>
<ElOption label="true" value="true" />
<ElOption label="false" value="false" />
</ElSelect>
<ElInput
v-else
v-model="row.defaultText"
data-testid="param-default"
:placeholder="t('query.params.defaultPlaceholder')"
/>
</template>
<span v-else class="query-mono">{{ row.defaultText === "" ? "—" : row.defaultText }}</span>
</template>
</ElTableColumn>
<ElTableColumn v-if="!readonly" :label="t('query.columns.actions')" width="90" align="right">
<template #default="{ row }">
<ElButton link type="danger" data-testid="param-remove" @click="remove(row.key)">
{{ t("query.actions.remove") }}
</ElButton>
</template>
</ElTableColumn>
</ElTable>
</div>
</template>
<style scoped>
.query-mono,
.query-mono :deep(input) {
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
}
</style>
@@ -0,0 +1,276 @@
<script setup lang="ts">
/**
* Trial-run panel: parameter inputs plus the outcome of the last run. It only displays; the
* page owns the footer button and the request. Outcomes are held in memory for display only.
* The five outcomes stay visually and verbally apart: success, empty (not an error), illegal
* type (contract mismatch), failure (timeout / connection / SQL kinds) and refused (disabled,
* circuit open). Sample values of sensitive-looking columns arrive already masked by the API.
*/
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { ElAlert, ElForm, ElFormItem, ElInput, ElOption, ElSelect, ElTable, ElTableColumn, ElTag } from "element-plus";
import { formatCell, formatDateTime } from "./format";
import type { PreviewSpec } from "./payload";
import { isConnectionKind, type PreviewView } from "./preview";
const props = defineProps<{
specs: PreviewSpec[];
modelValue: Record<string, string>;
view: PreviewView;
/** "current" runs the saved current version; "version" runs a frozen version. */
target: "current" | "version" | "draft";
versionNo?: number;
/** Unsaved edits exist: the run would use the saved current version, so it is blocked. */
dirty?: boolean;
/** Nothing saved yet (create): there is nothing to run. */
needSave?: boolean;
limits: { timeout_ms: number; max_rows: number } | null;
datasourceName: string;
invalid: string[];
}>();
const emit = defineEmits<{ "update:modelValue": [values: Record<string, string>] }>();
const { t, te } = useI18n();
const targetLabel = computed(() =>
props.target === "version"
? t("query.preview.targetVersion", { no: props.versionNo ?? "" })
: t("query.preview.targetCurrent"),
);
function setValue(name: string, value: string | undefined): void {
emit("update:modelValue", { ...props.modelValue, [name]: value ?? "" });
}
function placeholder(type: string): string {
return type === "datetime" ? "YYYY-MM-DD HH:MM:SS" : "";
}
const failureKind = computed(() => {
if (props.view.kind !== "failure") {
return "";
}
return te(`query.preview.failure.${props.view.failureKind}.title`) ? props.view.failureKind : "unknown";
});
/** Validation failures carry a stable reason; show its wording when we have one. */
const failureDetail = computed(() => {
if (props.view.kind !== "failure") {
return "";
}
const reason = props.view.outcome.details?.reason;
if (typeof reason === "string" && te(`query.errors.${reason}`)) {
return t(`query.errors.${reason}`);
}
return "";
});
const failureMaxRows = computed(() =>
props.view.kind === "failure" ? String(props.view.outcome.details?.max_rows ?? props.limits?.max_rows ?? "") : "",
);
const circuitUntil = computed(() => (props.view.kind === "circuit_open" ? formatDateTime(props.view.until) : ""));
const maskedColumns = computed(() =>
props.view.kind === "success" || props.view.kind === "empty" ? props.view.outcome.masked_columns ?? [] : [],
);
</script>
<template>
<section
class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4"
data-testid="preview-card"
>
<h3 class="mb-1 text-[14.5px] font-semibold">{{ t("query.preview.title") }}</h3>
<p class="mb-2.5 text-[var(--text-secondary)]">
{{ t("query.preview.target") }}<b data-testid="preview-target">{{ targetLabel }}</b>
</p>
<ElAlert
v-if="dirty"
class="mb-2.5"
type="warning"
data-testid="preview-dirty"
:title="t('query.preview.dirtyNote')"
show-icon
:closable="false"
/>
<ElAlert
v-else-if="needSave"
class="mb-2.5"
type="info"
data-testid="preview-need-save"
:title="t('query.preview.needSaveNote')"
show-icon
:closable="false"
/>
<p v-if="specs.length === 0" class="mb-3 text-[var(--text-muted)]" data-testid="preview-no-params">
{{ t("query.preview.noParams") }}
</p>
<ElForm v-else label-position="top" class="max-w-3xl" data-testid="preview-params" @submit.prevent>
<div class="grid grid-cols-1 gap-x-5 sm:grid-cols-3">
<ElFormItem
v-for="spec in specs"
:key="spec.name"
:label="`${spec.name} · ${spec.type}${spec.required ? ' *' : ''}`"
:error="invalid.includes(spec.name) ? t('query.preview.invalidValue') : ''"
:data-testid="`preview-param-${spec.name}`"
>
<ElSelect
v-if="spec.type === 'boolean'"
:model-value="modelValue[spec.name] ?? ''"
class="w-full"
clearable
:placeholder="t('query.preview.unset')"
@update:model-value="setValue(spec.name, $event)"
>
<ElOption label="true" value="true" />
<ElOption label="false" value="false" />
</ElSelect>
<ElInput
v-else
:model-value="modelValue[spec.name] ?? ''"
:placeholder="placeholder(spec.type)"
@update:model-value="setValue(spec.name, $event)"
/>
</ElFormItem>
</div>
</ElForm>
<div data-testid="preview-result" :data-status="view.kind" :data-failure-kind="failureKind">
<p
v-if="view.kind === 'none'"
data-testid="preview-none"
class="rounded-lg border border-[var(--border-subtle)] bg-[var(--bg-surface-soft)] px-3 py-2 text-[var(--text-secondary)]"
>
{{ t("query.preview.none") }}
</p>
<ElAlert
v-else-if="view.kind === 'running'"
type="info"
data-testid="preview-running"
:title="t('query.preview.running')"
show-icon
:closable="false"
/>
<template v-else-if="view.kind === 'success' || view.kind === 'empty'">
<ElAlert
:type="view.kind === 'success' ? 'success' : 'info'"
:title="t(`query.preview.${view.kind}.title`)"
:description="
view.kind === 'success'
? t('query.preview.success.body', { count: view.outcome.row_count })
: t('query.preview.empty.body')
"
show-icon
:closable="false"
/>
<ElTable
v-if="view.kind === 'success' && view.outcome.columns.length > 0"
class="mt-2.5"
:data="view.outcome.rows"
data-testid="preview-table"
>
<ElTableColumn
v-for="column in view.outcome.columns"
:key="column"
:prop="column"
min-width="130"
>
<template #header>
{{ column }}
<ElTag
v-if="maskedColumns.includes(column)"
type="warning"
effect="light"
size="small"
:data-testid="`masked-${column}`"
>
{{ t("query.preview.masked") }}
</ElTag>
</template>
<template #default="{ row }">{{ formatCell(row[column]) }}</template>
</ElTableColumn>
</ElTable>
</template>
<template v-else-if="view.kind === 'illegal_type'">
<ElAlert
type="warning"
:title="t('query.preview.illegal.title')"
:description="t('query.preview.illegal.body')"
show-icon
:closable="false"
/>
<ElTable class="mt-2.5" :data="view.outcome.details?.fields ?? []" data-testid="preview-problems">
<ElTableColumn :label="t('query.preview.illegal.row')" width="80">
<template #default="{ row }">{{ Number(row.row) + 1 }}</template>
</ElTableColumn>
<ElTableColumn prop="field" :label="t('query.preview.illegal.field')" min-width="140" />
<ElTableColumn prop="expected" :label="t('query.preview.illegal.expected')" min-width="120" />
<ElTableColumn prop="actual" :label="t('query.preview.illegal.actual')" min-width="120" />
</ElTable>
</template>
<template v-else-if="view.kind === 'failure'">
<ElAlert
:type="view.failureKind === 'timeout' ? 'warning' : 'error'"
:title="t(`query.preview.failure.${failureKind}.title`)"
:description="
[t(`query.preview.failure.${failureKind}.body`, { max_rows: failureMaxRows }), failureDetail]
.filter((text) => text !== '')
.join(' ')
"
show-icon
:closable="false"
/>
<p class="mt-2 text-xs text-[var(--text-secondary)]" data-testid="preview-failure-note">
{{
isConnectionKind(view.failureKind)
? t("query.preview.failure.noteCircuit")
: t("query.preview.failure.noteNoCircuit")
}}
</p>
</template>
<ElAlert
v-else-if="view.kind === 'disabled'"
type="warning"
:title="t('query.preview.disabled.title')"
:description="
view.scope === 'query' ? t('query.preview.disabled.queryBody') : t('query.preview.disabled.sourceBody')
"
show-icon
:closable="false"
/>
<ElAlert
v-else-if="view.kind === 'circuit_open'"
type="error"
:title="t('query.preview.circuit.title')"
:description="t('query.preview.circuit.body', { until: circuitUntil })"
show-icon
:closable="false"
/>
<ElAlert
v-else
type="error"
data-testid="preview-error"
:title="view.text"
show-icon
:closable="false"
/>
</div>
<p class="mt-2 text-xs text-[var(--text-secondary)]" data-testid="preview-meta">
<template v-if="limits">
timeout_ms={{ limits.timeout_ms }} · max_rows={{ limits.max_rows }} ·
{{ t("query.preview.datasource", { name: datasourceName }) }}<br />
</template>
{{ t("query.preview.onlyPreview") }}
</p>
</section>
</template>
+673
View File
@@ -0,0 +1,673 @@
<script setup lang="ts">
/**
* Query create and edit page (one form, two modes chosen by the route).
* Footer: 返回列表, 保存, 停用/启用, 试跑预览. Save creates v1 on create, or saves a new
* immutable version (and activates it) when content changed; metadata-only saves PATCH.
* Trial run uses the saved current version; unsaved edits disable 试跑预览.
*/
import { computed, nextTick, onMounted, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import {
ElAlert,
ElButton,
ElForm,
ElFormItem,
ElInput,
ElInputNumber,
ElMessage,
ElMessageBox,
ElOption,
ElSelect,
ElTag,
type FormInstance,
type FormRules,
} from "element-plus";
import { listDatasources } from "../datasources/client";
import type { Datasource } from "../datasources/types";
import {
createQuery,
disableQuery,
enableQuery,
getQuery,
getReferences,
listVersions,
previewCurrent,
saveQueryVersion,
updateQuery,
} from "./client";
import { describeError, isNotFound } from "./errors";
import { versionLabel } from "./format";
import IdentifierTags from "./IdentifierTags.vue";
import OutputsTable from "./OutputsTable.vue";
import ParamsTable from "./ParamsTable.vue";
import {
buildMetadataPayload,
buildPayload,
buildPreviewParams,
buildVersionContent,
emptyForm,
formFromRecord,
formSnapshot,
initialPreviewValues,
specsFromSchema,
} from "./payload";
import PreviewPanel from "./PreviewPanel.vue";
import { viewFromError, viewFromOutcome, type PreviewView } from "./preview";
import { ROWS_RANGE, TIMEOUT_RANGE, type QueryDetail, type VersionSummary } from "./types";
import {
firstOutputIssue,
firstParamIssue,
isFilledText,
isIntegerInRange,
sqlParamStatus,
} from "./validation";
import VersionsTable from "./VersionsTable.vue";
const { t, te } = useI18n();
const route = useRoute();
const router = useRouter();
/** How a template names an allowed identifier; built in script because the braces clash with the template syntax. */
const IDENTIFIER_EXAMPLE = `${"{{"}name${"}}"}`;
const isCreate = route.name === "query-create";
const queryId = isCreate ? "" : String(route.params.id ?? "");
const formRef = ref<FormInstance>();
const previewAnchor = ref<HTMLElement>();
const form = reactive(emptyForm());
const record = ref<QueryDetail | null>(null);
/** Text of the form as last saved (or loaded); a difference means unsaved edits. */
const savedSnapshot = ref(formSnapshot(form));
const loaded = ref(false);
const loadError = ref("");
const saving = ref(false);
const saveError = ref("");
const busy = ref(false);
const datasources = ref<Datasource[]>([]);
const datasourcesError = ref("");
const versions = ref<VersionSummary[]>([]);
const versionsError = ref("");
const references = ref<{ name?: string; id?: string }[] | null>(null);
const referencesError = ref("");
const previewView = ref<PreviewView>({ kind: "none" });
const previewValues = ref<Record<string, string>>({});
const previewInvalid = ref<string[]>([]);
type Validator = (rule: unknown, value: unknown, callback: (error?: Error) => void) => void;
const trigger = ["blur", "change"];
const requiredText = () => ({
validator: ((_rule, value, callback) =>
isFilledText(value) ? callback() : callback(new Error(t("query.form.required")))) as Validator,
trigger,
});
const integerIn = (min: number, max: number) => ({
validator: ((_rule, value, callback) => {
if (value === null || value === undefined || value === "") {
return callback(new Error(t("query.form.required")));
}
return isIntegerInRange(value, min, max)
? callback()
: callback(new Error(t("query.form.invalidRange", { min, max })));
}) as Validator,
trigger,
});
const rules = computed<FormRules>(() => ({
name: [
requiredText(),
{
max: 128,
message: t("query.form.nameTooLong"),
trigger,
},
],
datasource_id: [requiredText()],
sql_template: [requiredText()],
params: [
{
validator: ((_rule, _value, callback) => {
const problem = firstParamIssue(form.params);
return problem
? callback(new Error(t(`query.params.${problem.issue}`, { name: problem.name })))
: callback();
}) as Validator,
trigger,
},
],
outputs: [
{
validator: ((_rule, _value, callback) => {
const problem = firstOutputIssue(form.outputs);
return problem
? callback(new Error(t(`query.outputs.${problem.issue}`, { name: problem.name })))
: callback();
}) as Validator,
trigger,
},
],
timeout_ms: [integerIn(TIMEOUT_RANGE.min, TIMEOUT_RANGE.max)],
max_rows: [integerIn(ROWS_RANGE.min, ROWS_RANGE.max)],
}));
const databaseSources = computed(() => datasources.value.filter((item) => item.kind === "database"));
const recordEnabled = computed(() => record.value?.enabled === true);
const dirty = computed(() => !isCreate && record.value !== null && formSnapshot(form) !== savedSnapshot.value);
const previewSpecs = computed(() => specsFromSchema(record.value?.current.param_schema ?? []));
const previewRunning = computed(() => previewView.value.kind === "running");
const sqlStatus = computed(() =>
sqlParamStatus(
form.sql_template,
form.params.map((row) => row.name),
),
);
const sourceName = computed(
() => datasources.value.find((item) => item.id === record.value?.datasource_id)?.name ?? "",
);
const currentLabel = computed(
() => versionLabel(record.value?.current_version_no) ?? t("query.versions.none"),
);
const previewLimits = computed(() =>
record.value
? { timeout_ms: record.value.current.timeout_ms, max_rows: record.value.current.max_rows }
: null,
);
function applyRecord(row: QueryDetail): void {
record.value = row;
const next = formFromRecord(row);
Object.assign(form, next);
savedSnapshot.value = formSnapshot(form);
previewValues.value = initialPreviewValues(previewSpecs.value, previewValues.value);
}
function backToList(): void {
void router.push({ name: "query-list" });
}
function contentChanged(): boolean {
if (!record.value) {
return true;
}
const saved = buildVersionContent(formFromRecord(record.value));
const next = buildVersionContent(form);
return JSON.stringify(saved) !== JSON.stringify(next);
}
function metadataChanged(): boolean {
if (!record.value) {
return true;
}
const saved = buildMetadataPayload(formFromRecord(record.value));
const next = buildMetadataPayload(form);
return JSON.stringify(saved) !== JSON.stringify(next);
}
async function save(): Promise<void> {
saveError.value = "";
const valid = await formRef.value?.validate().catch(() => false);
if (!valid) {
return;
}
saving.value = true;
try {
if (isCreate) {
const created = await createQuery(buildPayload(form));
ElMessage.success(t("query.savedVersion", { version: "v1" }));
await router.replace({ name: "query-detail", params: { id: created.id } });
return;
}
if (metadataChanged()) {
await updateQuery(queryId, buildMetadataPayload(form));
}
if (contentChanged()) {
const version = await saveQueryVersion(queryId, buildVersionContent(form));
ElMessage.success(t("query.savedVersion", { version: `v${version.version_no}` }));
} else if (metadataChanged()) {
ElMessage.success(t("query.saved"));
} else {
ElMessage.success(t("query.saved"));
}
applyRecord(await getQuery(queryId));
previewView.value = { kind: "none" };
previewInvalid.value = [];
await refreshVersions();
} catch (error) {
saveError.value = describeError(error, t, te, "query.saveFailed");
} finally {
saving.value = false;
}
}
async function refreshVersions(): Promise<void> {
versionsError.value = "";
try {
versions.value = (await listVersions(queryId)).items;
} catch (error) {
versionsError.value = describeError(error, t, te, "query.versions.loadFailed");
}
}
async function onVersionActivated(): Promise<void> {
applyRecord(await getQuery(queryId));
await refreshVersions();
}
async function enable(): Promise<void> {
saveError.value = "";
busy.value = true;
try {
record.value = await enableQuery(queryId);
ElMessage.success(t("query.enabledDone"));
} catch (error) {
saveError.value = describeError(error, t, te, "query.saveFailed");
} finally {
busy.value = false;
}
}
async function disable(): Promise<void> {
if (!record.value) {
return;
}
try {
await ElMessageBox.confirm(
t("query.disableConfirm.body", { name: record.value.name }),
t("query.disableConfirm.title"),
{
type: "warning",
confirmButtonText: t("query.disableConfirm.ok"),
cancelButtonText: t("query.disableConfirm.cancel"),
},
);
} catch {
return;
}
saveError.value = "";
busy.value = true;
try {
record.value = await disableQuery(queryId);
ElMessage.success(t("query.disabledDone"));
} catch (error) {
saveError.value = describeError(error, t, te, "query.saveFailed");
} finally {
busy.value = false;
}
}
async function runPreview(): Promise<void> {
if (!record.value || dirty.value || previewRunning.value) {
return;
}
const { params, invalid } = buildPreviewParams(previewSpecs.value, previewValues.value);
previewInvalid.value = invalid;
if (invalid.length > 0) {
return;
}
previewView.value = { kind: "running" };
await nextTick();
previewAnchor.value?.scrollIntoView?.({ block: "nearest" });
try {
previewView.value = viewFromOutcome(await previewCurrent(queryId, params));
} catch (error) {
previewView.value = viewFromError(error, (failure) =>
describeError(failure, t, te, "query.preview.failedUnknown"),
);
}
await nextTick();
previewAnchor.value?.scrollIntoView?.({ block: "nearest" });
}
async function loadReferences(): Promise<void> {
try {
references.value = (await getReferences(queryId)).items as { name?: string; id?: string }[];
} catch (error) {
referencesError.value = describeError(error, t, te, "query.refs.loadFailed");
}
}
async function loadDatasources(): Promise<void> {
try {
datasources.value = (
await listDatasources({ page: 1, page_size: 100, sort_by: "name", sort_order: "asc" })
).items;
} catch (error) {
datasourcesError.value = describeError(error, t, te, "query.form.datasourcesFailed");
}
}
onMounted(async () => {
if (isCreate) {
await loadDatasources();
savedSnapshot.value = formSnapshot(form);
loaded.value = true;
return;
}
try {
const [row] = await Promise.all([getQuery(queryId), loadDatasources()]);
applyRecord(row);
loaded.value = true;
} catch (error) {
loadError.value = isNotFound(error) ? t("query.notFound") : describeError(error, t, te, "query.loadFailed");
return;
}
void refreshVersions();
void loadReferences();
// The list's 预览 arrives with ?preview=1 and only brings the trial-run panel into view.
if (route.query.preview === "1") {
await nextTick();
previewAnchor.value?.scrollIntoView?.({ block: "start" });
}
});
</script>
<template>
<div class="flex h-full min-h-0 flex-col">
<div class="min-h-0 flex-1 overflow-y-auto p-5" data-testid="query-scroll">
<ElAlert
v-if="loadError"
type="error"
data-testid="query-load-error"
:title="loadError"
show-icon
:closable="false"
/>
<template v-else-if="loaded">
<ElAlert
v-if="!isCreate && record && !record.enabled"
class="mb-3.5"
type="warning"
data-testid="query-disabled-note"
:title="t('query.disabledNote')"
show-icon
:closable="false"
/>
<ElAlert
v-if="saveError"
class="mb-3.5"
type="error"
data-testid="query-save-error"
:title="saveError"
show-icon
:closable="false"
/>
<ElAlert
v-if="datasourcesError"
class="mb-3.5"
type="error"
data-testid="query-datasources-error"
:title="datasourcesError"
show-icon
:closable="false"
/>
<ElForm
ref="formRef"
:model="form"
:rules="rules"
label-position="top"
data-testid="query-form"
@submit.prevent
>
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
<h3 class="mb-3 text-[14.5px] font-semibold">
{{ t("query.form.basic") }}
<span class="ml-2 font-normal text-[var(--text-muted)]" data-testid="basic-sub">
{{ isCreate ? t("query.form.subNew") : t("query.form.subSaved", { version: currentLabel }) }}
</span>
</h3>
<div class="grid max-w-3xl grid-cols-1 gap-x-6 sm:grid-cols-2">
<ElFormItem :label="t('query.form.name')" prop="name" data-testid="field-name">
<ElInput v-model="form.name" :placeholder="t('query.form.namePlaceholder')" />
</ElFormItem>
<ElFormItem :label="t('query.form.datasource')" prop="datasource_id" data-testid="field-datasource">
<ElSelect
v-model="form.datasource_id"
class="w-full"
:placeholder="t('query.form.datasourcePlaceholder')"
>
<ElOption
v-for="source in databaseSources"
:key="source.id"
:label="source.enabled ? source.name : `${source.name} ${t('query.form.datasourceOff')}`"
:value="source.id"
:disabled="!source.enabled"
/>
</ElSelect>
</ElFormItem>
<ElFormItem
:label="t('query.form.description')"
prop="description"
class="sm:col-span-2"
data-testid="field-description"
>
<ElInput v-model="form.description" type="textarea" :rows="2" />
</ElFormItem>
<ElFormItem :label="t('query.form.status')" data-testid="field-status">
<span v-if="isCreate" class="text-[var(--text-secondary)]">{{ t("query.form.statusNew") }}</span>
<span v-else class="inline-flex items-center gap-2">
<ElTag :type="recordEnabled ? 'success' : 'info'" effect="light" data-testid="status-tag">
{{ recordEnabled ? t("query.status.enabled") : t("query.status.disabled") }}
</ElTag>
<span class="text-[var(--text-muted)]">
{{ t("query.form.statusHint", { action: recordEnabled ? t("query.actions.disable") : t("query.actions.enable") }) }}
</span>
</span>
</ElFormItem>
</div>
</section>
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("query.form.sql") }}</h3>
<ElFormItem prop="sql_template" label-width="0" data-testid="field-sql">
<ElInput
v-model="form.sql_template"
class="query-sql"
type="textarea"
:rows="8"
:spellcheck="false"
:placeholder="t('query.form.sqlPlaceholder')"
/>
</ElFormItem>
<p class="mb-2 text-xs text-[var(--text-muted)]">{{ t("query.form.sqlHint") }}</p>
<div class="flex flex-wrap items-center gap-1.5" data-testid="sql-chips">
<span v-if="sqlStatus.used.length === 0 && sqlStatus.unused.length === 0" class="text-[var(--text-muted)]">
{{ t("query.sqlParams.none") }}
</span>
<template v-else>
<span class="text-[var(--text-muted)]">{{ t("query.sqlParams.used") }}</span>
<ElTag
v-for="name in sqlStatus.used"
:key="`u-${name}`"
:type="sqlStatus.undeclared.includes(name) ? 'danger' : 'success'"
effect="light"
:data-testid="sqlStatus.undeclared.includes(name) ? 'chip-undeclared' : 'chip-declared'"
:title="sqlStatus.undeclared.includes(name) ? t('query.sqlParams.undeclaredTitle') : undefined"
>
{{ sqlStatus.undeclared.includes(name) ? t("query.sqlParams.undeclared", { name }) : `:${name}` }}
</ElTag>
<ElTag
v-for="name in sqlStatus.unused"
:key="`n-${name}`"
type="info"
effect="light"
data-testid="chip-unused"
:title="t('query.sqlParams.unusedTitle')"
>
{{ t("query.sqlParams.unused", { name }) }}
</ElTag>
</template>
</div>
</section>
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
<h3 class="mb-1 text-[14.5px] font-semibold">{{ t("query.form.paramsTitle") }}</h3>
<p class="mb-2.5 text-xs text-[var(--text-muted)]">{{ t("query.form.paramsHint") }}</p>
<ElFormItem prop="params" label-width="0" data-testid="field-params">
<ParamsTable v-model="form.params" class="w-full" />
</ElFormItem>
</section>
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
<h3 class="mb-1 text-[14.5px] font-semibold">{{ t("query.form.outputsTitle") }}</h3>
<p class="mb-2.5 text-xs text-[var(--text-muted)]">{{ t("query.form.outputsHint") }}</p>
<ElFormItem prop="outputs" label-width="0" data-testid="field-outputs">
<OutputsTable v-model="form.outputs" class="w-full" />
</ElFormItem>
</section>
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
<h3 class="mb-1 text-[14.5px] font-semibold">{{ t("query.form.identifiersTitle") }}</h3>
<p class="mb-2.5 text-xs text-[var(--text-muted)]">
{{ t("query.form.identifiersHint", { example: IDENTIFIER_EXAMPLE }) }}
</p>
<IdentifierTags v-model="form.identifiers" />
</section>
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("query.form.limits") }}</h3>
<div class="grid max-w-3xl grid-cols-1 gap-x-6 sm:grid-cols-2">
<ElFormItem label="timeout_ms" prop="timeout_ms" data-testid="field-timeout">
<ElInputNumber
v-model="form.timeout_ms"
style="width: 100%"
:controls="false"
:precision="0"
align="left"
/>
</ElFormItem>
<ElFormItem label="max_rows" prop="max_rows" data-testid="field-max-rows">
<ElInputNumber
v-model="form.max_rows"
style="width: 100%"
:controls="false"
:precision="0"
align="left"
/>
</ElFormItem>
</div>
<p class="text-xs text-[var(--text-muted)]">
{{ t("query.form.limitsHint", { timeout: TIMEOUT_RANGE.max, rows: ROWS_RANGE.max }) }}
</p>
</section>
</ElForm>
<div ref="previewAnchor">
<PreviewPanel
v-model="previewValues"
:specs="previewSpecs"
:view="previewView"
target="current"
:dirty="dirty"
:need-save="isCreate"
:limits="previewLimits"
:datasource-name="sourceName"
:invalid="previewInvalid"
/>
</div>
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
<h3 class="mb-1 text-[14.5px] font-semibold">{{ t("query.versions.title") }}</h3>
<p class="mb-2.5 text-xs text-[var(--text-muted)]">{{ t("query.versions.hint") }}</p>
<p
v-if="isCreate"
data-testid="versions-create-note"
class="rounded-lg border border-dashed border-[var(--border-default)] px-5 py-4 text-center text-[var(--text-secondary)]"
>
{{ t("query.versions.emptyCreate") }}
</p>
<ElAlert
v-else-if="versionsError"
type="error"
data-testid="versions-error"
:title="versionsError"
show-icon
:closable="false"
/>
<VersionsTable
v-else
:definition-id="queryId"
:versions="versions"
:active-no="record?.current_version_no ?? undefined"
@activated="onVersionActivated"
/>
</section>
<section
class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4"
data-testid="query-references"
>
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("query.refs.title") }}</h3>
<ElAlert
v-if="referencesError"
type="error"
:title="referencesError"
show-icon
:closable="false"
/>
<ul v-else-if="references && references.length > 0" data-testid="references-list">
<li v-for="(item, index) in references" :key="item.id ?? index">{{ item.name ?? item.id }}</li>
</ul>
<p
v-else
data-testid="references-empty"
class="rounded-lg border border-dashed border-[var(--border-default)] px-5 py-4 text-center text-[var(--text-secondary)]"
>
{{ t("query.refs.empty") }}
</p>
</section>
</template>
</div>
<footer
data-testid="query-footer"
class="flex shrink-0 flex-wrap items-center justify-center gap-2 border-t border-[var(--border-subtle)] bg-white px-5 py-3"
>
<ElButton data-testid="footer-back" @click="backToList">{{ t("query.actions.backToList") }}</ElButton>
<template v-if="loaded && !loadError">
<ElButton
type="primary"
data-testid="footer-save"
:loading="saving"
:disabled="busy || previewRunning"
@click="save"
>
{{ t("query.actions.save") }}
</ElButton>
<template v-if="!isCreate">
<ElButton
v-if="recordEnabled"
type="danger"
plain
data-testid="footer-disable"
:disabled="busy || saving"
@click="disable"
>
{{ t("query.actions.disable") }}
</ElButton>
<ElButton v-else type="success" plain data-testid="footer-enable" :disabled="busy || saving" @click="enable">
{{ t("query.actions.enable") }}
</ElButton>
</template>
<ElButton
data-testid="footer-preview"
:disabled="isCreate || dirty || previewRunning || saving"
:title="isCreate || dirty ? t('query.actions.previewNeedSave') : undefined"
@click="runPreview"
>
{{ t("query.actions.runPreview") }}
</ElButton>
</template>
</footer>
</div>
</template>
<style scoped>
.query-sql :deep(textarea) {
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
font-size: 12.5px;
line-height: 1.6;
}
</style>
@@ -0,0 +1,32 @@
<script setup lang="ts">
/**
* Gate for every query page. Only watchman-admin sees the child routes.
* Other signed-in roles get the "cannot enter" panel, and no child page is created,
* so no query request is sent for them. The backend enforces the same rule.
* Child pages are keyed by URL, so create -> detail and detail -> version reload cleanly.
*/
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { RouterView } from "vue-router";
import { allowsQueries } from "../session";
import { useAuthStore } from "../stores/auth";
const { t } = useI18n();
const auth = useAuthStore();
const allowed = computed(() => allowsQueries(auth.user?.roles ?? []));
</script>
<template>
<RouterView v-if="allowed" v-slot="{ Component, route }">
<component :is="Component" :key="route.fullPath" />
</RouterView>
<div v-else class="h-full overflow-auto p-5">
<div
data-testid="query-denied"
class="rounded-lg border border-dashed border-[var(--border-default)] bg-white px-5 py-14 text-center"
>
<h3 class="mb-1.5 text-[15px] font-semibold">{{ t("query.denied.title") }}</h3>
<p class="text-[var(--text-secondary)]">{{ t("query.denied.body") }}</p>
</div>
</div>
</template>
+400
View File
@@ -0,0 +1,400 @@
<script setup lang="ts">
/**
* Query list. Filters are drafts until 查询; sort and page hit the server.
* Row actions: 打开 / 切换版本 / 预览 (D26). Disabled rows stay visible; 预览 is disabled
* with a title. 预览 opens the detail scrolled to the trial-run panel.
*/
import { computed, onMounted, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import {
ElAlert,
ElButton,
ElDialog,
ElInput,
ElOption,
ElPagination,
ElSelect,
ElTable,
ElTableColumn,
ElTag,
vLoading,
} from "element-plus";
import { listDatasources } from "../datasources/client";
import type { Datasource } from "../datasources/types";
import { LIST_DEFAULT_PAGE_SIZE, LIST_PAGE_SIZES, actionsColumnWidth } from "../tableLayout";
import { listQueries, listVersions } from "./client";
import { describeError } from "./errors";
import { formatDateTime, versionLabel } from "./format";
import type { QuerySummary, VersionSummary } from "./types";
import VersionsTable from "./VersionsTable.vue";
const { t, te } = useI18n();
const router = useRouter();
const items = ref<QuerySummary[]>([]);
const total = ref(0);
const datasources = ref<Datasource[]>([]);
const loading = ref(true);
const loadError = ref("");
/** Draft filters edited in the toolbar; applied only on 查询 / 重置. */
const draft = reactive({ name: "", datasourceId: "", status: "" });
const applied = reactive({ name: "", datasourceId: "", status: "" });
const page = ref(1);
const pageSize = ref(LIST_DEFAULT_PAGE_SIZE);
const sortBy = ref("updated_at");
const sortOrder = ref<"asc" | "desc">("desc");
const datasourceNames = computed(() => new Map(datasources.value.map((item) => [item.id, item.name])));
const hasAppliedFilters = computed(
() =>
applied.name.trim() !== "" || applied.datasourceId !== "" || applied.status !== "",
);
const actionsWidth = actionsColumnWidth(3);
const switchOpen = ref(false);
const switchRow = ref<QuerySummary | null>(null);
const switchVersions = ref<VersionSummary[]>([]);
const switchLoading = ref(false);
const switchError = ref("");
async function loadOptions(): Promise<void> {
try {
// Option lists need a wide page; not the table page size.
const sources = await listDatasources({ page: 1, page_size: 100, sort_by: "name", sort_order: "asc" });
datasources.value = sources.items;
} catch {
datasources.value = [];
}
}
async function load(): Promise<void> {
loading.value = true;
loadError.value = "";
try {
const enabled =
applied.status === "enabled" ? true : applied.status === "disabled" ? false : undefined;
const result = await listQueries({
name: applied.name.trim() || undefined,
datasource_id: applied.datasourceId || undefined,
enabled,
sort_by: sortBy.value,
sort_order: sortOrder.value,
page: page.value,
page_size: pageSize.value,
});
items.value = result.items;
total.value = result.total;
} catch (error) {
loadError.value = describeError(error, t, te, "query.list.loadFailed");
items.value = [];
total.value = 0;
} finally {
loading.value = false;
}
}
function applyFilters(): void {
applied.name = draft.name;
applied.datasourceId = draft.datasourceId;
applied.status = draft.status;
page.value = 1;
void load();
}
function resetFilters(): void {
draft.name = "";
draft.datasourceId = "";
draft.status = "";
applied.name = "";
applied.datasourceId = "";
applied.status = "";
page.value = 1;
void load();
}
function onSortChange(payload: { prop: string | null; order: string | null }): void {
const propMap: Record<string, string> = {
name: "name",
datasource: "datasource_name",
status: "enabled",
currentVersion: "current_version_no",
updated_at: "updated_at",
};
const next = payload.prop ? propMap[payload.prop] : undefined;
if (!next || !payload.order) {
sortBy.value = "updated_at";
sortOrder.value = "desc";
} else {
sortBy.value = next;
sortOrder.value = payload.order === "ascending" ? "asc" : "desc";
}
page.value = 1;
void load();
}
function onPageChange(next: number): void {
page.value = next;
void load();
}
function onSizeChange(next: number): void {
pageSize.value = next;
page.value = 1;
void load();
}
function asRow(source: unknown): QuerySummary {
return source as QuerySummary;
}
function rowClass({ row }: { row: unknown }): string {
return asRow(row).enabled ? "" : "query-row-off";
}
function sourceName(source: unknown): string {
const row = asRow(source);
return datasourceNames.value.get(row.datasource_id) ?? row.datasource_id;
}
function currentVersion(source: unknown): string {
return versionLabel(asRow(source).current_version_no) ?? t("query.versions.none");
}
function openCreate(): void {
void router.push({ name: "query-create" });
}
function openDetail(source: unknown): void {
void router.push({ name: "query-detail", params: { id: asRow(source).id } });
}
function openPreview(source: unknown): void {
void router.push({ name: "query-detail", params: { id: asRow(source).id }, query: { preview: "1" } });
}
async function openSwitch(source: unknown): Promise<void> {
const row = asRow(source);
switchRow.value = row;
switchOpen.value = true;
switchLoading.value = true;
switchError.value = "";
switchVersions.value = [];
try {
switchVersions.value = (await listVersions(row.id)).items;
} catch (error) {
switchError.value = describeError(error, t, te, "query.versions.loadFailed");
} finally {
switchLoading.value = false;
}
}
async function onSwitchActivated(): Promise<void> {
switchOpen.value = false;
await load();
}
onMounted(async () => {
await loadOptions();
await load();
});
</script>
<template>
<div class="h-full overflow-auto p-5" data-testid="query-list">
<div class="mb-3 flex flex-wrap items-center gap-2" data-testid="query-list-toolbar">
<div class="w-[200px]" data-testid="query-filter-name">
<ElInput v-model="draft.name" clearable :placeholder="t('query.list.filterName')" />
</div>
<div class="w-[200px]" data-testid="query-filter-datasource">
<ElSelect
v-model="draft.datasourceId"
clearable
class="w-full"
:placeholder="t('query.list.filterDatasource')"
>
<ElOption
v-for="source in datasources"
:key="source.id"
:label="source.name"
:value="source.id"
/>
</ElSelect>
</div>
<div class="w-[140px]" data-testid="query-filter-status">
<ElSelect
v-model="draft.status"
clearable
class="w-full"
:placeholder="t('query.list.filterStatus')"
>
<ElOption :label="t('query.status.enabled')" value="enabled" />
<ElOption :label="t('query.status.disabled')" value="disabled" />
</ElSelect>
</div>
<ElButton type="primary" data-testid="query-filter-search" @click="applyFilters">
{{ t("query.list.filterSearch") }}
</ElButton>
<ElButton data-testid="query-filter-reset" @click="resetFilters">
{{ t("query.list.filterReset") }}
</ElButton>
<div class="ml-auto">
<ElButton type="primary" data-testid="query-create" @click="openCreate">
{{ t("query.list.create") }}
</ElButton>
</div>
</div>
<ElAlert
v-if="loadError"
type="error"
data-testid="query-load-error"
:title="loadError"
show-icon
:closable="false"
/>
<div
v-else-if="!loading && total === 0 && !hasAppliedFilters"
data-testid="query-empty"
class="rounded-lg border border-dashed border-[var(--border-default)] bg-white px-5 py-14 text-center"
>
<h3 class="mb-1.5 text-[15px] font-semibold">{{ t("query.list.empty") }}</h3>
<p class="text-[var(--text-secondary)]">{{ t("query.list.emptyHint") }}</p>
</div>
<div
v-else-if="!loading && total === 0 && hasAppliedFilters"
data-testid="query-filter-empty"
class="rounded-lg border border-dashed border-[var(--border-default)] bg-white px-5 py-14 text-center"
>
<h3 class="mb-1.5 text-[15px] font-semibold">{{ t("query.list.filterEmpty") }}</h3>
<p class="text-[var(--text-secondary)]">{{ t("query.list.filterEmptyHint") }}</p>
</div>
<template v-else>
<ElTable
v-loading="loading"
:data="items"
row-key="id"
data-testid="query-table"
:default-sort="{ prop: 'updated_at', order: 'descending' }"
:row-class-name="rowClass"
@sort-change="onSortChange"
>
<ElTableColumn
prop="name"
:label="t('query.columns.name')"
min-width="180"
sortable="custom"
/>
<ElTableColumn
prop="datasource"
:label="t('query.columns.datasource')"
min-width="160"
sortable="custom"
>
<template #default="{ row }">{{ sourceName(row) }}</template>
</ElTableColumn>
<ElTableColumn
prop="status"
:label="t('query.columns.status')"
min-width="110"
sortable="custom"
>
<template #default="{ row }">
<ElTag :type="row.enabled ? 'success' : 'info'" effect="light" data-testid="row-status">
{{ row.enabled ? t("query.status.enabled") : t("query.status.disabled") }}
</ElTag>
</template>
</ElTableColumn>
<ElTableColumn
prop="currentVersion"
:label="t('query.columns.currentVersion')"
min-width="120"
sortable="custom"
>
<template #default="{ row }">{{ currentVersion(row) }}</template>
</ElTableColumn>
<ElTableColumn
prop="updated_at"
:label="t('query.columns.updatedAt')"
min-width="150"
sortable="custom"
>
<template #default="{ row }">{{ formatDateTime(row.updated_at) }}</template>
</ElTableColumn>
<ElTableColumn
:label="t('query.columns.actions')"
:width="actionsWidth"
align="right"
fixed="right"
>
<template #default="{ row }">
<div class="whitespace-nowrap" :data-testid="`query-row-${row.id}`">
<ElButton link type="primary" data-testid="row-open" @click="openDetail(row)">
{{ t("query.actions.open") }}
</ElButton>
<ElButton link type="primary" data-testid="row-switch-version" @click="openSwitch(row)">
{{ t("query.actions.switchVersion") }}
</ElButton>
<ElButton
link
type="primary"
data-testid="row-preview"
:disabled="!row.enabled"
:title="row.enabled ? undefined : t('query.actions.previewDisabledWhy')"
@click="openPreview(row)"
>
{{ t("query.actions.preview") }}
</ElButton>
</div>
</template>
</ElTableColumn>
</ElTable>
<div class="mt-3 flex justify-end" data-testid="query-pagination">
<ElPagination
background
layout="total, sizes, prev, pager, next"
:total="total"
:page-size="pageSize"
:page-sizes="[...LIST_PAGE_SIZES]"
:current-page="page"
@current-change="onPageChange"
@size-change="onSizeChange"
/>
</div>
</template>
<ElDialog
v-model="switchOpen"
align-center
append-to-body
:close-on-click-modal="false"
:title="t('query.versions.switchTitle', { name: switchRow?.name ?? '' })"
width="680px"
data-testid="query-switch-dialog"
>
<ElAlert
v-if="switchError"
type="error"
:title="switchError"
show-icon
:closable="false"
/>
<div v-else v-loading="switchLoading">
<VersionsTable
v-if="switchRow"
:definition-id="switchRow.id"
:versions="switchVersions"
:active-no="switchRow.current_version_no ?? undefined"
@activated="onSwitchActivated"
/>
</div>
</ElDialog>
</div>
</template>
<style scoped>
:deep(.query-row-off td) {
color: var(--text-muted);
}
</style>
@@ -0,0 +1,279 @@
<script setup lang="ts">
/**
* Read-only page of one frozen version. Footer: 返回列表, 返回查询, 激活此版本 (when not
* current), 试跑预览. Breadcrumb: 预警平台 / 查询 / 详情 / 版本 vN.
*/
import { computed, nextTick, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import { ElAlert, ElButton, ElDescriptions, ElDescriptionsItem, ElMessage, ElTag } from "element-plus";
import { listDatasources } from "../datasources/client";
import type { Datasource } from "../datasources/types";
import { activateQueryVersion, getQuery, getVersion, listVersions, previewVersion } from "./client";
import { describeError, isNotFound } from "./errors";
import { formatDateTime } from "./format";
import IdentifierTags from "./IdentifierTags.vue";
import OutputsTable from "./OutputsTable.vue";
import ParamsTable from "./ParamsTable.vue";
import { buildPreviewParams, initialPreviewValues, rowsFromContent, specsFromSchema } from "./payload";
import PreviewPanel from "./PreviewPanel.vue";
import { viewFromError, viewFromOutcome, type PreviewView } from "./preview";
import type { OutputRow, ParamRow, QueryDetail, QueryVersion, VersionSummary } from "./types";
import VersionsTable from "./VersionsTable.vue";
const { t, te } = useI18n();
const route = useRoute();
const router = useRouter();
const queryId = String(route.params.id ?? "");
const versionNo = Number(route.params.versionNo);
const previewAnchor = ref<HTMLElement>();
const record = ref<QueryDetail | null>(null);
const version = ref<QueryVersion | null>(null);
const params = ref<ParamRow[]>([]);
const outputs = ref<OutputRow[]>([]);
const versions = ref<VersionSummary[]>([]);
const datasources = ref<Datasource[]>([]);
const loaded = ref(false);
const loadError = ref("");
const previewView = ref<PreviewView>({ kind: "none" });
const previewValues = ref<Record<string, string>>({});
const previewInvalid = ref<string[]>([]);
const previewSpecs = computed(() => specsFromSchema(version.value?.param_schema ?? []));
const previewRunning = computed(() => previewView.value.kind === "running");
const sourceName = computed(
() => datasources.value.find((item) => item.id === record.value?.datasource_id)?.name ?? "",
);
const isActive = computed(
() => version.value !== null && version.value.version_no === record.value?.current_version_no,
);
const previewLimits = computed(() =>
version.value ? { timeout_ms: version.value.timeout_ms, max_rows: version.value.max_rows } : null,
);
const activating = ref(false);
function backToList(): void {
void router.push({ name: "query-list" });
}
function backToQuery(): void {
void router.push({ name: "query-detail", params: { id: queryId } });
}
async function activate(): Promise<void> {
if (!version.value || isActive.value || activating.value) {
return;
}
activating.value = true;
try {
record.value = await activateQueryVersion(queryId, version.value.version_no);
ElMessage.success(t("query.versions.activated", { version: `v${version.value.version_no}` }));
versions.value = (await listVersions(queryId)).items;
} catch (error) {
loadError.value = describeError(error, t, te, "query.saveFailed");
} finally {
activating.value = false;
}
}
async function onActivatedFromTable(): Promise<void> {
record.value = await getQuery(queryId);
versions.value = (await listVersions(queryId)).items;
}
async function runPreview(): Promise<void> {
if (!version.value || previewRunning.value) {
return;
}
const built = buildPreviewParams(previewSpecs.value, previewValues.value);
previewInvalid.value = built.invalid;
if (built.invalid.length > 0) {
return;
}
previewView.value = { kind: "running" };
await nextTick();
previewAnchor.value?.scrollIntoView?.({ block: "nearest" });
try {
previewView.value = viewFromOutcome(await previewVersion(queryId, versionNo, built.params));
} catch (error) {
previewView.value = viewFromError(error, (failure) =>
describeError(failure, t, te, "query.preview.failedUnknown"),
);
}
await nextTick();
previewAnchor.value?.scrollIntoView?.({ block: "nearest" });
}
onMounted(async () => {
if (!Number.isInteger(versionNo) || versionNo < 1) {
loadError.value = t("query.versionNotFound");
return;
}
try {
const [row, frozen] = await Promise.all([getQuery(queryId), getVersion(queryId, versionNo)]);
record.value = row;
version.value = frozen;
const rows = rowsFromContent(frozen);
params.value = rows.params;
outputs.value = rows.outputs;
previewValues.value = initialPreviewValues(specsFromSchema(frozen.param_schema));
loaded.value = true;
} catch (error) {
loadError.value = isNotFound(error)
? t("query.versionNotFound")
: describeError(error, t, te, "query.loadFailed");
return;
}
// The list and the names only decorate the page; a failure of either must not hide the version.
void listVersions(queryId)
.then((result) => {
versions.value = result.items;
})
.catch(() => undefined);
void listDatasources({ page: 1, page_size: 100, sort_by: "name", sort_order: "asc" })
.then((result) => {
datasources.value = result.items;
})
.catch(() => undefined);
});
</script>
<template>
<div class="flex h-full min-h-0 flex-col">
<div class="min-h-0 flex-1 overflow-y-auto p-5" data-testid="query-scroll">
<ElAlert
v-if="loadError"
type="error"
data-testid="query-load-error"
:title="loadError"
show-icon
:closable="false"
/>
<template v-else-if="loaded && record && version">
<ElAlert
class="mb-3.5"
type="info"
data-testid="version-frozen-note"
:title="t('query.versions.frozenNote', { version: `v${version.version_no}` })"
show-icon
:closable="false"
/>
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
<h3 class="mb-3 text-[14.5px] font-semibold">
{{ t("query.versions.info") }}
<ElTag type="info" effect="plain" class="ml-2" data-testid="version-readonly-tag">
{{ t("query.versions.readonly") }}
</ElTag>
</h3>
<ElDescriptions :column="2" data-testid="version-info">
<ElDescriptionsItem :label="t('query.versions.query')">{{ record.name }}</ElDescriptionsItem>
<ElDescriptionsItem :label="t('query.versions.version')">
<span data-testid="version-number">v{{ version.version_no }}</span>
<ElTag v-if="isActive" type="success" effect="light" class="ml-1.5" data-testid="version-active-tag">
{{ t("query.versions.current") }}
</ElTag>
</ElDescriptionsItem>
<ElDescriptionsItem :label="t('query.versions.publishedAt')">
{{ formatDateTime(version.published_at) }}
</ElDescriptionsItem>
<ElDescriptionsItem :label="t('query.versions.publishedBy')">
{{ version.published_by ?? "" }}
</ElDescriptionsItem>
<ElDescriptionsItem :label="t('query.columns.datasource')">{{ sourceName }}</ElDescriptionsItem>
</ElDescriptions>
</section>
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("query.form.sql") }}</h3>
<pre
data-testid="version-sql"
class="query-sql-frozen overflow-auto whitespace-pre-wrap rounded-md border border-[var(--border-subtle)] bg-[var(--bg-surface-soft)] px-3 py-2.5"
>{{ version.sql_template }}</pre
>
</section>
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("query.form.paramsTitle") }}</h3>
<ParamsTable :model-value="params" readonly />
</section>
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("query.form.outputsTitle") }}</h3>
<OutputsTable :model-value="outputs" readonly />
</section>
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("query.form.identifiersTitle") }}</h3>
<IdentifierTags :model-value="version.allowed_identifiers" readonly />
</section>
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("query.form.limits") }}</h3>
<ElDescriptions :column="2" data-testid="version-limits">
<ElDescriptionsItem label="timeout_ms">{{ version.timeout_ms }}</ElDescriptionsItem>
<ElDescriptionsItem label="max_rows">{{ version.max_rows }}</ElDescriptionsItem>
</ElDescriptions>
</section>
<div ref="previewAnchor">
<PreviewPanel
v-model="previewValues"
:specs="previewSpecs"
:view="previewView"
target="version"
:version-no="version.version_no"
:limits="previewLimits"
:datasource-name="sourceName"
:invalid="previewInvalid"
/>
</div>
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("query.versions.title") }}</h3>
<VersionsTable
:definition-id="queryId"
:versions="versions"
:current-no="version.version_no"
:active-no="record.current_version_no ?? undefined"
@activated="onActivatedFromTable"
/>
</section>
</template>
</div>
<footer
data-testid="query-footer"
class="flex shrink-0 flex-wrap items-center justify-center gap-2 border-t border-[var(--border-subtle)] bg-white px-5 py-3"
>
<ElButton data-testid="footer-back" @click="backToList">{{ t("query.actions.backToList") }}</ElButton>
<template v-if="loaded && !loadError">
<ElButton data-testid="footer-query" @click="backToQuery">{{ t("query.actions.backToQuery") }}</ElButton>
<ElButton
v-if="!isActive"
type="primary"
plain
data-testid="footer-activate"
:loading="activating"
@click="activate"
>
{{ t("query.actions.activate") }}
</ElButton>
<ElButton data-testid="footer-preview" :disabled="previewRunning" @click="runPreview">
{{ t("query.actions.runPreview") }}
</ElButton>
</template>
</footer>
</div>
</template>
<style scoped>
.query-sql-frozen {
margin: 0;
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
font-size: 12.5px;
line-height: 1.6;
}
</style>
@@ -0,0 +1,133 @@
<script setup lang="ts">
/**
* Versions of one query, newest first. Opening a row goes to the read-only version page.
* Activate sets current_version_no without creating a new version (D26).
*/
import { ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { ElButton, ElMessage, ElTable, ElTableColumn, ElTag } from "element-plus";
import { activateQueryVersion } from "./client";
import { describeError } from "./errors";
import { formatDateTime } from "./format";
import type { VersionSummary } from "./types";
const props = defineProps<{
definitionId: string;
versions: VersionSummary[];
/** Currently active version (D26). */
activeNo?: number;
/** Highlight a row (e.g. the version page's own number). */
currentNo?: number;
/** When false, hide activate actions (read-only contexts can still show the badge). */
allowActivate?: boolean;
}>();
const emit = defineEmits<{ activated: [] }>();
const { t, te } = useI18n();
const router = useRouter();
const activating = ref<number | null>(null);
function open(source: unknown): void {
const row = source as VersionSummary;
void router.push({
name: "query-version",
params: { id: props.definitionId, versionNo: String(row.version_no) },
});
}
async function activate(source: unknown): Promise<void> {
const row = source as VersionSummary;
if (row.version_no === props.activeNo || activating.value !== null) {
return;
}
activating.value = row.version_no;
try {
await activateQueryVersion(props.definitionId, row.version_no);
ElMessage.success(t("query.versions.activated", { version: `v${row.version_no}` }));
emit("activated");
} catch (error) {
ElMessage.error(describeError(error, t, te, "query.saveFailed"));
} finally {
activating.value = null;
}
}
function rowClass({ row }: { row: unknown }): string {
const no = (row as VersionSummary).version_no;
return no === props.currentNo || no === props.activeNo ? "query-version-current" : "";
}
</script>
<template>
<div data-testid="versions-block">
<p
v-if="versions.length === 0"
data-testid="versions-empty"
class="rounded-lg border border-dashed border-[var(--border-default)] px-5 py-4 text-center text-[var(--text-secondary)]"
>
{{ t("query.versions.empty") }}
</p>
<ElTable
v-else
:data="versions"
row-key="id"
data-testid="versions-table"
:row-class-name="rowClass"
>
<ElTableColumn :label="t('query.versions.version')" min-width="140">
<template #default="{ row }">
<span class="query-mono">v{{ row.version_no }}</span>
<ElTag
v-if="row.version_no === activeNo"
type="success"
effect="light"
class="ml-1.5"
data-testid="version-active-tag"
>
{{ t("query.versions.current") }}
</ElTag>
<ElTag
v-else-if="versions[0]?.version_no === row.version_no"
type="info"
effect="light"
class="ml-1.5"
>
{{ t("query.versions.latest") }}
</ElTag>
</template>
</ElTableColumn>
<ElTableColumn :label="t('query.versions.publishedAt')" min-width="150">
<template #default="{ row }">{{ formatDateTime(row.published_at) }}</template>
</ElTableColumn>
<ElTableColumn prop="published_by" :label="t('query.versions.publishedBy')" min-width="130" />
<ElTableColumn :label="t('query.columns.actions')" width="168" align="right">
<template #default="{ row }">
<ElButton link type="primary" :data-testid="`version-open-${row.version_no}`" @click="open(row)">
{{ t("query.actions.open") }}
</ElButton>
<ElButton
v-if="allowActivate !== false && row.version_no !== activeNo"
link
type="primary"
:data-testid="`version-activate-${row.version_no}`"
:loading="activating === row.version_no"
@click="activate(row)"
>
{{ t("query.actions.activate") }}
</ElButton>
</template>
</ElTableColumn>
</ElTable>
</div>
</template>
<style scoped>
.query-mono {
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
}
:deep(.query-version-current td) {
background: var(--el-fill-color-lighter);
}
</style>
+103
View File
@@ -0,0 +1,103 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@watchman/api", async () => {
const actual = await vi.importActual<typeof import("@watchman/api")>("@watchman/api");
return { ...actual, requestJson: vi.fn() };
});
import { requestJson } from "@watchman/api";
import {
createQuery,
disableQuery,
enableQuery,
getReferences,
getVersion,
listQueries,
listVersions,
previewDraft,
previewVersion,
saveQueryVersion,
activateQueryVersion,
updateQuery,
} from "./client";
import { buildPayload, emptyForm } from "./payload";
const mocked = vi.mocked(requestJson);
function lastCall(): { url: string; init: RequestInit } {
const [url, init] = mocked.mock.calls[mocked.mock.calls.length - 1];
return { url: String(url), init: (init ?? {}) as RequestInit };
}
describe("query client", () => {
beforeEach(() => {
mocked.mockReset();
mocked.mockResolvedValue({});
});
it("reads use GET on the /queries routes", async () => {
await listQueries();
expect(lastCall().url).toBe("/queries");
await listQueries({ name: "温度", page: 2, page_size: 10, sort_by: "name", sort_order: "asc" });
expect(lastCall().url).toContain("/queries?");
expect(lastCall().url).toContain("name=");
expect(lastCall().url).toContain("page=2");
await listVersions("q 1");
expect(lastCall().url).toBe("/queries/q%201/versions");
await getVersion("q1", 3);
expect(lastCall().url).toBe("/queries/q1/versions/3");
await getReferences("q1");
expect(lastCall().url).toBe("/queries/q1/references");
expect(lastCall().init.method).toBeUndefined();
});
it("create and update send the whole draft as JSON", async () => {
const form = { ...emptyForm("ds-1"), name: "n", sql_template: "SELECT 1" };
await createQuery(buildPayload(form));
expect(lastCall().url).toBe("/queries");
expect(lastCall().init.method).toBe("POST");
expect(JSON.parse(String(lastCall().init.body)).datasource_id).toBe("ds-1");
await updateQuery("q1", buildPayload(form));
expect(lastCall().url).toBe("/queries/q1");
expect(lastCall().init.method).toBe("PATCH");
expect(new Headers(lastCall().init.headers).get("Content-Type")).toBe("application/json");
});
it("enable, disable and activate are body-less POSTs", async () => {
await enableQuery("q1");
expect(lastCall()).toMatchObject({ url: "/queries/q1/enable", init: { method: "POST" } });
await disableQuery("q1");
expect(lastCall().url).toBe("/queries/q1/disable");
await activateQueryVersion("q1", 2);
expect(lastCall().url).toBe("/queries/q1/versions/2/activate");
expect(lastCall().init.body).toBeUndefined();
});
it("saveQueryVersion posts content as a new version", async () => {
await saveQueryVersion("q1", {
sql_template: "SELECT 1",
param_schema: [],
output_schema: [],
allowed_identifiers: [],
timeout_ms: 1000,
max_rows: 10,
});
expect(lastCall().url).toBe("/queries/q1/versions");
expect(lastCall().init.method).toBe("POST");
expect(JSON.parse(String(lastCall().init.body)).sql_template).toBe("SELECT 1");
});
it("previews post only the parameter values", async () => {
await previewDraft("q1", { line_code: "L1" });
expect(lastCall().url).toBe("/queries/q1/preview");
expect(JSON.parse(String(lastCall().init.body))).toEqual({ params: { line_code: "L1" } });
await previewVersion("q1", 2, {});
expect(lastCall().url).toBe("/queries/q1/versions/2/preview");
expect(JSON.parse(String(lastCall().init.body))).toEqual({ params: {} });
});
it("unwraps what requestJson returns", async () => {
mocked.mockResolvedValueOnce({ items: [{ id: "q1" }] });
expect(await listQueries()).toEqual({ items: [{ id: "q1" }] });
});
});
+124
View File
@@ -0,0 +1,124 @@
/** Calls to the /queries routes. Each one returns the unwrapped envelope data. */
import { api } from "../api";
import type { QueryPayload } from "./payload";
import type {
PreviewOutcome,
QueryDetail,
QueryList,
QueryListParams,
QueryReferences,
QueryVersion,
VersionList,
} from "./types";
const JSON_HEADERS = { "Content-Type": "application/json" };
function base(id: string): string {
return `/queries/${encodeURIComponent(id)}`;
}
function toQuery(params?: QueryListParams): string {
if (!params) {
return "";
}
const q = new URLSearchParams();
if (params.name) q.set("name", params.name);
if (params.datasource_id) q.set("datasource_id", params.datasource_id);
if (params.enabled !== undefined) q.set("enabled", String(params.enabled));
if (params.sort_by) q.set("sort_by", params.sort_by);
if (params.sort_order) q.set("sort_order", params.sort_order);
if (params.page !== undefined) q.set("page", String(params.page));
if (params.page_size !== undefined) q.set("page_size", String(params.page_size));
const text = q.toString();
return text ? `?${text}` : "";
}
export function listQueries(params?: QueryListParams): Promise<QueryList> {
return api<QueryList>(`/queries${toQuery(params)}`);
}
export function getQuery(id: string): Promise<QueryDetail> {
return api<QueryDetail>(base(id));
}
export function createQuery(payload: QueryPayload): Promise<QueryDetail> {
return api<QueryDetail>("/queries", {
method: "POST",
headers: JSON_HEADERS,
body: JSON.stringify(payload),
});
}
/** Metadata-only PATCH (name / description / datasource). */
export function updateQuery(
id: string,
payload: Pick<QueryPayload, "name" | "description" | "datasource_id">,
): Promise<QueryDetail> {
return api<QueryDetail>(base(id), {
method: "PATCH",
headers: JSON_HEADERS,
body: JSON.stringify(payload),
});
}
export type VersionContent = Omit<QueryPayload, "name" | "description" | "datasource_id">;
/** Save content as the next immutable version and make it current (D26). */
export function saveQueryVersion(id: string, content: VersionContent): Promise<QueryVersion> {
return api<QueryVersion>(`${base(id)}/versions`, {
method: "POST",
headers: JSON_HEADERS,
body: JSON.stringify(content),
});
}
export function activateQueryVersion(id: string, versionNo: number): Promise<QueryDetail> {
return api<QueryDetail>(`${base(id)}/versions/${encodeURIComponent(String(versionNo))}/activate`, {
method: "POST",
});
}
export function disableQuery(id: string): Promise<QueryDetail> {
return api<QueryDetail>(`${base(id)}/disable`, { method: "POST" });
}
export function enableQuery(id: string): Promise<QueryDetail> {
return api<QueryDetail>(`${base(id)}/enable`, { method: "POST" });
}
export function listVersions(id: string): Promise<VersionList> {
return api<VersionList>(`${base(id)}/versions`);
}
export function getVersion(id: string, versionNo: number): Promise<QueryVersion> {
return api<QueryVersion>(`${base(id)}/versions/${encodeURIComponent(String(versionNo))}`);
}
/** Trial-run the current active version. */
export function previewCurrent(id: string, params: Record<string, unknown>): Promise<PreviewOutcome> {
return api<PreviewOutcome>(`${base(id)}/preview`, {
method: "POST",
headers: JSON_HEADERS,
body: JSON.stringify({ params }),
});
}
/** @deprecated use previewCurrent */
export const previewDraft = previewCurrent;
export function previewVersion(
id: string,
versionNo: number,
params: Record<string, unknown>,
): Promise<PreviewOutcome> {
return api<PreviewOutcome>(`${base(id)}/versions/${encodeURIComponent(String(versionNo))}/preview`, {
method: "POST",
headers: JSON_HEADERS,
body: JSON.stringify({ params }),
});
}
export function getReferences(id: string): Promise<QueryReferences> {
return api<QueryReferences>(`${base(id)}/references`);
}
+120
View File
@@ -0,0 +1,120 @@
import { describe, expect, it } from "vitest";
import { BusinessError } from "@watchman/api";
import { describeError, isDisabledRejection, isNotFound } from "./errors";
import { isConnectionKind, viewFromError, viewFromOutcome } from "./preview";
import type { PreviewOutcome } from "./types";
const MESSAGES: Record<string, string> = {
"query.errors.duplicate_name": "名称已存在",
"query.errors.disabled": "查询已停用",
"codes.40000": "参数错误",
"codes.42000": "权限不足",
fallback: "未完成",
};
const t = (key: string) => MESSAGES[key] ?? key;
const te = (key: string) => key in MESSAGES;
function business(
code: number,
status: number,
details: Record<string, unknown> = {},
): BusinessError {
return new BusinessError({ code, message: "server text must never show", details, status, requestId: "r" });
}
describe("describeError", () => {
it("prefers the stable reason", () => {
expect(describeError(business(40000, 409, { reason: "duplicate_name" }), t, te, "fallback")).toBe("名称已存在");
});
it("falls back to the numeric code, then to the fallback text", () => {
expect(describeError(business(42000, 403), t, te, "fallback")).toBe("权限不足 (42000)");
expect(describeError(business(40000, 400, { reason: "unheard_of" }), t, te, "fallback")).toBe("参数错误 (40000)");
expect(describeError(business(50000, 500), t, te, "fallback")).toBe("未完成 (50000)");
});
it("uses the fallback for anything that is not an API error", () => {
expect(describeError(new TypeError("network"), t, te, "fallback")).toBe("未完成");
});
it("never shows the server message text", () => {
expect(describeError(business(40000, 400), t, te, "fallback")).not.toContain("server text");
});
});
describe("status checks", () => {
it("not found is HTTP 404 (the code stays 40000)", () => {
expect(isNotFound(business(40000, 404, { reason: "not_found" }))).toBe(true);
expect(isNotFound(business(40000, 400))).toBe(false);
expect(isNotFound(new Error("x"))).toBe(false);
});
it("a disabled rejection is HTTP 409 with reason disabled", () => {
expect(isDisabledRejection(business(40000, 409, { reason: "disabled" }))).toBe(true);
expect(isDisabledRejection(business(40000, 409, { reason: "duplicate_name" }))).toBe(false);
expect(isDisabledRejection(business(40000, 400, { reason: "disabled" }))).toBe(false);
});
});
describe("preview views", () => {
const base = { id: "q1", version_no: 1, source: "current" as const, message: "m" };
it("keeps success, empty, illegal type and failure apart", () => {
const success: PreviewOutcome = {
...base,
status: "success",
columns: ["a"],
rows: [{ a: 1 }],
row_count: 1,
masked_columns: [],
};
const empty: PreviewOutcome = { ...success, status: "empty", rows: [], row_count: 0 };
const illegal: PreviewOutcome = {
...base,
status: "illegal_type",
columns: ["a"],
details: { fields: [{ field: "a", expected: "integer", actual: "str", row: 0 }] },
};
const timeout: PreviewOutcome = { ...base, status: "failure", failure_kind: "timeout", details: {} };
expect(viewFromOutcome(success).kind).toBe("success");
expect(viewFromOutcome(empty).kind).toBe("empty");
expect(viewFromOutcome(illegal).kind).toBe("illegal_type");
const failure = viewFromOutcome(timeout);
expect(failure.kind).toBe("failure");
expect(failure.kind === "failure" && failure.failureKind).toBe("timeout");
});
it("maps a disabled source and an open circuit to their own panels", () => {
const disabled: PreviewOutcome = { ...base, status: "failure", failure_kind: "disabled", details: { reason: "disabled" } };
expect(viewFromOutcome(disabled)).toEqual({ kind: "disabled", scope: "datasource" });
const open: PreviewOutcome = {
...base,
status: "failure",
failure_kind: "circuit_open",
details: { circuit_open_until: "2026-11-18T09:30:00+00:00" },
};
expect(viewFromOutcome(open)).toEqual({ kind: "circuit_open", until: "2026-11-18T09:30:00+00:00" });
const noTime: PreviewOutcome = { ...base, status: "failure", failure_kind: "circuit_open", details: {} };
expect(viewFromOutcome(noTime)).toEqual({ kind: "circuit_open", until: null });
});
it("a failure without a kind is still shown as a failure", () => {
const view = viewFromOutcome({ ...base, status: "failure", failure_kind: null, details: {} });
expect(view.kind === "failure" && view.failureKind).toBe("unknown");
});
it("only connection-class kinds count toward the circuit", () => {
expect(["unreachable", "auth_failed", "rejected"].every(isConnectionKind)).toBe(true);
expect(["timeout", "sql_error", "limit_exceeded", "validation"].some(isConnectionKind)).toBe(false);
});
it("a 409 from the preview route is the disabled panel, other errors are plain text", () => {
const describe_ = (error: unknown) => describeError(error, t, te, "fallback");
expect(viewFromError(business(40000, 409, { reason: "disabled" }), describe_)).toEqual({
kind: "disabled",
scope: "query",
});
expect(viewFromError(business(42000, 403), describe_)).toEqual({ kind: "error", text: "权限不足 (42000)" });
expect(viewFromError(new Error("boom"), describe_)).toEqual({ kind: "error", text: "未完成" });
});
});
+33
View File
@@ -0,0 +1,33 @@
/**
* Turns a failed API call into one line for the user. No server message text is shown:
* the stable `details.reason` picks the wording, then the numeric code, then a fallback.
*/
import { BusinessError } from "@watchman/api";
type Translate = (key: string, named?: Record<string, unknown>) => string;
type Exists = (key: string) => boolean;
export function describeError(error: unknown, t: Translate, te: Exists, fallbackKey: string): string {
if (!(error instanceof BusinessError)) {
return t(fallbackKey);
}
const reason = error.details.reason;
if (typeof reason === "string" && te(`query.errors.${reason}`)) {
return t(`query.errors.${reason}`);
}
if (te(`codes.${error.code}`)) {
return `${t(`codes.${error.code}`)} (${error.code})`;
}
return `${t(fallbackKey)} (${error.code})`;
}
/** True when the API says the thing does not exist (HTTP 404, reason not_found). */
export function isNotFound(error: unknown): boolean {
return error instanceof BusinessError && error.status === 404;
}
/** True when a preview was refused because the query definition is disabled (HTTP 409). */
export function isDisabledRejection(error: unknown): boolean {
return error instanceof BusinessError && error.status === 409 && error.details.reason === "disabled";
}
+33
View File
@@ -0,0 +1,33 @@
/** Display helpers for query rows and preview samples. */
function pad(value: number): string {
return String(value).padStart(2, "0");
}
/** "2026-11-17 09:12" in the browser's time zone, or an empty string when unset or invalid. */
export function formatDateTime(iso: string | null | undefined): string {
if (!iso) {
return "";
}
const date = new Date(iso);
if (Number.isNaN(date.getTime())) {
return "";
}
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
/** One preview cell as text: SQL NULL is shown as NULL, objects as JSON. */
export function formatCell(value: unknown): string {
if (value === null || value === undefined) {
return "NULL";
}
if (typeof value === "object") {
return JSON.stringify(value);
}
return String(value);
}
/** "v3" for a version number, or null when never published. */
export function versionLabel(versionNo: number | null | undefined): string | null {
return versionNo === null || versionNo === undefined ? null : `v${versionNo}`;
}
@@ -0,0 +1,97 @@
import { describe, expect, it } from "vitest";
import zhCN from "../../locales/zh-CN/common.json";
import zhTW from "../../locales/zh-TW/common.json";
import en from "../../locales/en/common.json";
import th from "../../locales/th/common.json";
function leafKeys(value: unknown, prefix = ""): string[] {
if (value === null || typeof value !== "object") {
return [prefix];
}
return Object.entries(value as Record<string, unknown>).flatMap(([key, child]) =>
leafKeys(child, prefix ? `${prefix}.${key}` : key),
);
}
function texts(value: unknown): string[] {
if (typeof value === "string") {
return [value];
}
if (value && typeof value === "object") {
return Object.values(value as Record<string, unknown>).flatMap(texts);
}
return [];
}
describe("query locale keys", () => {
const base = leafKeys((zhCN as { query: unknown }).query).sort();
it.each([
["zh-TW", zhTW],
["en", en],
["th", th],
])("%s has the same query keys as zh-CN", (_name, messages) => {
expect(leafKeys((messages as { query: unknown }).query).sort()).toEqual(base);
});
it.each([
["zh-CN", zhCN],
["zh-TW", zhTW],
["en", en],
["th", th],
])("%s has the nav entries and every text is filled", (_name, messages) => {
const nav = (messages as { nav: Record<string, string> }).nav;
expect(nav.queries).toBeTruthy();
expect(nav.version).toContain("{no}");
expect(texts((messages as { query: unknown }).query).every((text) => text.trim() !== "")).toBe(true);
});
it("names every backend reason the console can show", () => {
for (const reason of [
"duplicate_name",
"datasource_not_found",
"template_empty",
"param_schema_invalid",
"output_schema_invalid",
"limit_invalid",
"disabled",
"version_conflict",
"missing_param",
"undeclared_param",
]) {
expect(leafKeys(zhCN)).toContain(`query.errors.${reason}`);
}
});
it("has the page-level messages the pages call by name", () => {
for (const key of [
"query.saved",
"query.savedVersion",
"query.saveFailed",
"query.loadFailed",
"query.notFound",
"query.versionNotFound",
"query.enabledDone",
"query.disabledDone",
"query.disabledNote",
"query.preview.failedUnknown",
"query.preview.targetCurrent",
"query.versions.loadFailed",
"query.versions.activated",
"query.form.datasourcesFailed",
]) {
expect(leafKeys(zhCN)).toContain(key);
}
});
it("keeps the footer wording after removing draft/publish", () => {
const query = (zhCN as unknown as { query: { actions: Record<string, string> } }).query;
expect(query.actions.backToList).toBe("返回列表");
expect(query.actions.save).toBe("保存");
expect(query.actions.activate).toBe("激活此版本");
expect(query.actions.switchVersion).toBe("切换版本");
expect(query.actions.disable).toBe("停用");
expect(query.actions.enable).toBe("启用");
expect(query.actions.runPreview).toBe("试跑预览");
});
});
@@ -0,0 +1,160 @@
import { describe, expect, it } from "vitest";
import {
buildPayload,
buildPreviewParams,
emptyForm,
formFromRecord,
formSnapshot,
initialPreviewValues,
newOutputRow,
newParamRow,
specsFromSchema,
} from "./payload";
import type { QueryDetail, QueryForm } from "./types";
function filled(overrides: Partial<QueryForm> = {}): QueryForm {
return {
...emptyForm("ds-1"),
name: " 产线温度采样 ",
description: "",
sql_template: "SELECT lot_no FROM process_readings WHERE line_code = :line_code\n",
params: [
{ key: 1, name: "line_code", type: "string", required: true, defaultText: "" },
{ key: 2, name: "min_temp", type: "number", required: false, defaultText: "0.5" },
{ key: 3, name: "active", type: "boolean", required: false, defaultText: "true" },
],
outputs: [{ key: 4, name: " lot_no ", type: "string" }],
identifiers: ["process_readings", "process_readings"],
timeout_ms: 5000,
max_rows: 200,
...overrides,
};
}
describe("buildPayload", () => {
it("trims text, nulls a blank description and keeps the SQL untouched", () => {
const payload = buildPayload(filled());
expect(payload.name).toBe("产线温度采样");
expect(payload.description).toBeNull();
expect(payload.sql_template.endsWith("\n")).toBe(true);
expect(payload.datasource_id).toBe("ds-1");
});
it("converts parameter defaults by type and omits blank ones", () => {
const { param_schema } = buildPayload(filled());
expect(param_schema[0]).toEqual({ name: "line_code", type: "string", required: true });
expect("default" in param_schema[0]).toBe(false);
expect(param_schema[1]).toEqual({ name: "min_temp", type: "number", required: false, default: 0.5 });
expect(param_schema[2].default).toBe(true);
});
it("builds the output schema and dedupes identifiers", () => {
const payload = buildPayload(filled());
expect(payload.output_schema).toEqual([{ name: "lot_no", type: "string" }]);
expect(payload.allowed_identifiers).toEqual(["process_readings"]);
expect(payload.timeout_ms).toBe(5000);
expect(payload.max_rows).toBe(200);
});
it("carries only draft fields: no tenant, version, publisher or enabled flag", () => {
const keys = Object.keys(buildPayload(filled())).sort();
expect(keys).toEqual([
"allowed_identifiers",
"datasource_id",
"description",
"max_rows",
"name",
"output_schema",
"param_schema",
"sql_template",
"timeout_ms",
]);
});
it("new rows start required for parameters and string typed", () => {
expect(newParamRow()).toMatchObject({ name: "", type: "string", required: true, defaultText: "" });
expect(newOutputRow()).toMatchObject({ name: "", type: "string" });
expect(newParamRow().key).not.toBe(newParamRow().key);
});
});
describe("record round trip", () => {
const record: QueryDetail = {
id: "q-1",
name: "产线温度采样",
description: null,
datasource_id: "ds-1",
enabled: true,
current_version_no: 2,
latest_version_no: 2,
latest_published_version_no: 2,
created_at: null,
updated_at: null,
current: {
sql_template: "SELECT 1 WHERE a = :a",
param_schema: [
{ name: "a", type: "integer", required: true, default: 7 },
{ name: "b", type: "boolean", required: false, default: false },
{ name: "c", type: "datetime", required: false },
],
output_schema: [{ name: "n", type: "nullish" }],
allowed_identifiers: ["t"],
timeout_ms: 10000,
max_rows: 100,
},
};
it("shows stored defaults as text and sends them back unchanged", () => {
const form = formFromRecord(record);
expect(form.params.map((row) => row.defaultText)).toEqual(["7", "false", ""]);
const payload = buildPayload(form);
expect(payload.param_schema).toEqual(record.current.param_schema);
expect(payload.output_schema).toEqual(record.current.output_schema);
expect(payload.description).toBeNull();
});
it("a snapshot of a freshly loaded form equals itself and changes on an edit", () => {
const form = formFromRecord(record);
const saved = formSnapshot(form);
expect(formSnapshot(formFromRecord(record))).toBe(saved);
form.sql_template += " ";
expect(formSnapshot(form)).not.toBe(saved);
});
});
describe("preview params", () => {
const specs = specsFromSchema([
{ name: "line_code", type: "string", required: true },
{ name: "since", type: "datetime", required: false, default: "2026-11-17 00:00:00" },
{ name: "limit", type: "integer", required: false },
]);
it("starts from defaults and keeps what the user typed", () => {
expect(initialPreviewValues(specs)).toEqual({
line_code: "",
since: "2026-11-17 00:00:00",
limit: "",
});
expect(initialPreviewValues(specs, { line_code: "L1", gone: "x" })).toEqual({
line_code: "L1",
since: "2026-11-17 00:00:00",
limit: "",
});
});
it("omits blank values and converts the rest by type", () => {
const result = buildPreviewParams(specs, { line_code: "L1", since: "", limit: "5" });
expect(result.params).toEqual({ line_code: "L1", limit: 5 });
expect(result.invalid).toEqual([]);
});
it("reports values that do not fit instead of sending them", () => {
const result = buildPreviewParams(specs, { line_code: "L1", since: "", limit: "five" });
expect(result.invalid).toEqual(["limit"]);
expect("limit" in result.params).toBe(false);
});
it("sends nothing for a query without parameters", () => {
expect(buildPreviewParams([], {})).toEqual({ params: {}, invalid: [] });
});
});
+214
View File
@@ -0,0 +1,214 @@
/**
* Request bodies for create / metadata update / save-version, and form ↔ API mapping.
* Boundary: tenant, version pointers, publisher and enabled are never sent.
*/
import {
LIMIT_DEFAULTS,
type OutputRow,
type OutputSchemaItem,
type ParamRow,
type ParamSchemaItem,
type QueryDetail,
type QueryDraft,
type QueryForm,
type QueryVersion,
} from "./types";
import { isValueTextValid, parseValueText } from "./validation";
export type QueryPayload = {
name: string;
description: string | null;
datasource_id: string;
sql_template: string;
param_schema: ParamSchemaItem[];
output_schema: OutputSchemaItem[];
allowed_identifiers: string[];
timeout_ms: number;
max_rows: number;
};
let rowCounter = 0;
export function nextRowKey(): number {
rowCounter += 1;
return rowCounter;
}
export function newParamRow(): ParamRow {
// Required is the backend's default for a parameter.
return { key: nextRowKey(), name: "", type: "string", required: true, defaultText: "" };
}
export function newOutputRow(): OutputRow {
return { key: nextRowKey(), name: "", type: "string" };
}
export function emptyForm(datasourceId = ""): QueryForm {
return {
name: "",
description: "",
datasource_id: datasourceId,
sql_template: "",
params: [],
outputs: [],
identifiers: [],
timeout_ms: LIMIT_DEFAULTS.timeout_ms,
max_rows: LIMIT_DEFAULTS.max_rows,
};
}
/** Text shown in the default input for a stored default value. */
export function defaultToText(value: unknown): string {
if (value === undefined || value === null) {
return "";
}
return typeof value === "string" ? value : String(value);
}
export function paramsToRows(items: ParamSchemaItem[]): ParamRow[] {
return items.map((item) => ({
key: nextRowKey(),
name: item.name,
type: item.type,
required: item.required !== false,
defaultText: defaultToText(item.default),
}));
}
export function outputsToRows(items: OutputSchemaItem[]): OutputRow[] {
return items.map((item) => ({ key: nextRowKey(), name: item.name, type: item.type }));
}
export function formFromRecord(record: QueryDetail): QueryForm {
const current = record.current;
return {
name: record.name,
description: record.description ?? "",
datasource_id: record.datasource_id,
sql_template: current.sql_template,
params: paramsToRows(current.param_schema),
outputs: outputsToRows(current.output_schema),
identifiers: [...current.allowed_identifiers],
timeout_ms: current.timeout_ms,
max_rows: current.max_rows,
};
}
/** Form-like rows for the frozen content of a version (read-only view). */
export function rowsFromContent(content: QueryDraft | QueryVersion): {
params: ParamRow[];
outputs: OutputRow[];
} {
return { params: paramsToRows(content.param_schema), outputs: outputsToRows(content.output_schema) };
}
/** A blank default text means "no default" and sends no `default` key. */
export function buildParamSchema(rows: ParamRow[]): ParamSchemaItem[] {
return rows.map((row) => {
const item: ParamSchemaItem = { name: row.name.trim(), type: row.type, required: row.required };
if (row.defaultText.trim() !== "") {
item.default = parseValueText(row.type, row.defaultText);
}
return item;
});
}
export function buildOutputSchema(rows: OutputRow[]): OutputSchemaItem[] {
return rows.map((row) => ({ name: row.name.trim(), type: row.type }));
}
/** Full body for POST /queries (create with v1) and POST .../versions (save content). */
export function buildPayload(form: QueryForm): QueryPayload {
const description = form.description.trim();
return {
name: form.name.trim(),
description: description === "" ? null : description,
datasource_id: form.datasource_id,
sql_template: form.sql_template,
param_schema: buildParamSchema(form.params),
output_schema: buildOutputSchema(form.outputs),
allowed_identifiers: [...new Set(form.identifiers)],
timeout_ms: Number(form.timeout_ms),
max_rows: Number(form.max_rows),
};
}
/** Metadata-only PATCH body. */
export function buildMetadataPayload(
form: QueryForm,
): Pick<QueryPayload, "name" | "description" | "datasource_id"> {
const description = form.description.trim();
return {
name: form.name.trim(),
description: description === "" ? null : description,
datasource_id: form.datasource_id,
};
}
/** Content-only body for POST .../versions. */
export function buildVersionContent(
form: QueryForm,
): Omit<QueryPayload, "name" | "description" | "datasource_id"> {
const full = buildPayload(form);
return {
sql_template: full.sql_template,
param_schema: full.param_schema,
output_schema: full.output_schema,
allowed_identifiers: full.allowed_identifiers,
timeout_ms: full.timeout_ms,
max_rows: full.max_rows,
};
}
/** Stable text of the form's saved-relevant content, to tell unsaved edits from saved ones. */
export function formSnapshot(form: QueryForm): string {
return JSON.stringify(buildPayload(form));
}
export type PreviewSpec = { name: string; type: string; required: boolean; defaultText: string };
export function specsFromSchema(items: ParamSchemaItem[]): PreviewSpec[] {
return items.map((item) => ({
name: item.name,
type: item.type,
required: item.required !== false,
defaultText: defaultToText(item.default),
}));
}
/** Initial preview inputs: the declared defaults, keeping what the user already typed. */
export function initialPreviewValues(
specs: PreviewSpec[],
previous: Record<string, string> = {},
): Record<string, string> {
const values: Record<string, string> = {};
for (const spec of specs) {
values[spec.name] = previous[spec.name] ?? spec.defaultText;
}
return values;
}
/**
* Body of the preview calls. Blank inputs are omitted so the server applies the default or
* reports the missing parameter. `invalid` lists names whose text does not fit the type.
*/
export function buildPreviewParams(
specs: PreviewSpec[],
values: Record<string, string>,
): { params: Record<string, unknown>; invalid: string[] } {
const params: Record<string, unknown> = {};
const invalid: string[] = [];
for (const spec of specs) {
const text = values[spec.name] ?? "";
if (text.trim() === "") {
continue;
}
if (!isValueTextValid(spec.type, text)) {
invalid.push(spec.name);
continue;
}
params[spec.name] = parseValueText(spec.type, text);
}
return { params, invalid };
}
+63
View File
@@ -0,0 +1,63 @@
/**
* Maps a preview response (or a refused call) to the panel the console shows.
* Boundary: pure mapping, no I/O. The outcome is only ever held in memory for display; the
* console never stores sample rows. Server message text is not shown, only the status and
* failure kind pick the wording.
*/
import type { PreviewFailure, PreviewIllegalType, PreviewOutcome, PreviewRows } from "./types";
import { isDisabledRejection } from "./errors";
export const FAILURE_KINDS = [
"timeout",
"unreachable",
"auth_failed",
"rejected",
"sql_error",
"limit_exceeded",
"validation",
"engine_readonly_unsupported",
] as const;
export type PreviewView =
| { kind: "none" }
| { kind: "running" }
| { kind: "success"; outcome: PreviewRows }
| { kind: "empty"; outcome: PreviewRows }
| { kind: "illegal_type"; outcome: PreviewIllegalType }
| { kind: "failure"; failureKind: string; outcome: PreviewFailure }
/** scope "query": the definition is disabled (HTTP 409); "datasource": its source is disabled. */
| { kind: "disabled"; scope: "query" | "datasource" }
| { kind: "circuit_open"; until: string | null }
| { kind: "error"; text: string };
/** Connection-class failures count against the datasource circuit (M03); the others do not. */
export function isConnectionKind(kind: string): boolean {
return kind === "unreachable" || kind === "auth_failed" || kind === "rejected";
}
export function viewFromOutcome(outcome: PreviewOutcome): PreviewView {
if (outcome.status === "illegal_type") {
return { kind: "illegal_type", outcome };
}
if (outcome.status !== "failure") {
return outcome.status === "success" ? { kind: "success", outcome } : { kind: "empty", outcome };
}
const kind = outcome.failure_kind ?? "unknown";
if (kind === "disabled") {
return { kind: "disabled", scope: "datasource" };
}
if (kind === "circuit_open") {
const until = outcome.details?.circuit_open_until;
return { kind: "circuit_open", until: typeof until === "string" ? until : null };
}
return { kind: "failure", failureKind: kind, outcome };
}
/** A refused preview call: 409 disabled gets its own panel; anything else is a plain error. */
export function viewFromError(error: unknown, describe: (error: unknown) => string): PreviewView {
if (isDisabledRejection(error)) {
return { kind: "disabled", scope: "query" };
}
return { kind: "error", text: describe(error) };
}
+148
View File
@@ -0,0 +1,148 @@
/** Query definition shapes returned by /queries, and the form rows the console edits. */
export const VALUE_TYPES = ["string", "integer", "number", "boolean", "datetime"] as const;
export type ValueType = (typeof VALUE_TYPES)[number];
/** "nullish" is output-only: the column carries no type constraint. */
export const OUTPUT_TYPES = [...VALUE_TYPES, "nullish"] as const;
export type OutputType = (typeof OUTPUT_TYPES)[number];
/** Server defaults and caps. A value above a cap is capped by the server; below 1 is refused. */
export const LIMIT_DEFAULTS = { timeout_ms: 10000, max_rows: 100 } as const;
export const TIMEOUT_RANGE = { min: 1, max: 300000 } as const;
export const ROWS_RANGE = { min: 1, max: 10000 } as const;
export const MAX_OUTPUT_NAME = 128;
export type ParamSchemaItem = {
name: string;
type: ValueType;
required: boolean;
default?: unknown;
};
export type OutputSchemaItem = { name: string; type: OutputType };
/** Editable draft content, keyed like the PATCH body. */
export type QueryDraft = {
sql_template: string;
param_schema: ParamSchemaItem[];
output_schema: OutputSchemaItem[];
allowed_identifiers: string[];
timeout_ms: number;
max_rows: number;
};
export type QuerySummary = {
id: string;
name: string;
description: string | null;
datasource_id: string;
enabled: boolean;
current_version_no: number | null;
latest_version_no: number | null;
/** @deprecated alias of latest_version_no */
latest_published_version_no?: number | null;
created_at: string | null;
updated_at: string | null;
};
export type QueryDetail = QuerySummary & { current: QueryDraft };
export type QueryList = {
items: QuerySummary[];
total: number;
page: number;
page_size: number;
};
/** Console list query params; omit fields the server should ignore. */
export type QueryListParams = {
name?: string;
datasource_id?: string;
enabled?: boolean;
sort_by?: string;
sort_order?: "asc" | "desc";
page?: number;
page_size?: number;
};
export type VersionSummary = {
id: string;
definition_id: string;
version_no: number;
published_at: string | null;
published_by: string | null;
};
export type QueryVersion = VersionSummary & QueryDraft;
export type VersionList = { id: string; items: VersionSummary[] };
export type QueryReferences = { id: string; items: unknown[] };
export type PreviewFailureKind =
| "validation"
| "disabled"
| "circuit_open"
| "timeout"
| "unreachable"
| "auth_failed"
| "rejected"
| "limit_exceeded"
| "sql_error"
| "engine_readonly_unsupported";
type PreviewBase = {
id: string;
version_no: number | null;
source: "current" | "version" | "draft";
message: string;
};
export type PreviewRows = PreviewBase & {
status: "success" | "empty";
columns: string[];
rows: Record<string, unknown>[];
row_count: number;
masked_columns: string[];
};
export type TypeProblem = { field: string; expected: string; actual: string; row: number };
export type PreviewIllegalType = PreviewBase & {
status: "illegal_type";
columns: string[];
details: { fields?: TypeProblem[] };
};
export type PreviewFailure = PreviewBase & {
status: "failure";
failure_kind: PreviewFailureKind | string | null;
details: Record<string, unknown>;
};
/** Response of both preview routes. Nothing in it is stored on the server. */
export type PreviewOutcome = PreviewRows | PreviewIllegalType | PreviewFailure;
/** One editable parameter row. `defaultText` is the raw input; the payload converts it by type. */
export type ParamRow = {
key: number;
name: string;
type: ValueType;
required: boolean;
defaultText: string;
};
export type OutputRow = { key: number; name: string; type: OutputType };
export type QueryForm = {
name: string;
description: string;
datasource_id: string;
sql_template: string;
params: ParamRow[];
outputs: OutputRow[];
identifiers: string[];
timeout_ms: number | null;
max_rows: number | null;
};
@@ -0,0 +1,139 @@
import { describe, expect, it } from "vitest";
import type { OutputRow, ParamRow } from "./types";
import {
detectSqlParams,
firstOutputIssue,
firstParamIssue,
isFilledText,
isIntegerInRange,
isValidIdentifier,
isValueTextValid,
parseValueText,
sqlParamStatus,
} from "./validation";
const param = (overrides: Partial<ParamRow> = {}): ParamRow => ({
key: 1,
name: "line_code",
type: "string",
required: true,
defaultText: "",
...overrides,
});
const output = (overrides: Partial<OutputRow> = {}): OutputRow => ({
key: 1,
name: "lot_no",
type: "string",
...overrides,
});
describe("basic checks", () => {
it("isFilledText needs a visible character", () => {
expect(isFilledText("SELECT 1")).toBe(true);
expect(isFilledText(" ")).toBe(false);
expect(isFilledText(undefined)).toBe(false);
});
it("limits use whole numbers inside the server caps", () => {
expect(isIntegerInRange(1, 1, 300000)).toBe(true);
expect(isIntegerInRange(300000, 1, 300000)).toBe(true);
expect(isIntegerInRange(300001, 1, 300000)).toBe(false);
expect(isIntegerInRange(0, 1, 10000)).toBe(false);
expect(isIntegerInRange(1.5, 1, 10000)).toBe(false);
expect(isIntegerInRange(null, 1, 10000)).toBe(false);
});
it("identifiers follow the backend pattern", () => {
expect(isValidIdentifier("process_readings")).toBe(true);
expect(isValidIdentifier("_x1")).toBe(true);
expect(isValidIdentifier("1abc")).toBe(false);
expect(isValidIdentifier("a.b")).toBe(false);
expect(isValidIdentifier("a b")).toBe(false);
expect(isValidIdentifier("")).toBe(false);
});
});
describe("detectSqlParams", () => {
it("finds :name markers once each", () => {
expect(detectSqlParams("WHERE a = :line_code AND b >= :since AND c = :line_code")).toEqual([
"line_code",
"since",
]);
});
it("skips casts, quoted text and comments", () => {
expect(detectSqlParams("SELECT x::int, ':not_this', 'it''s :nor_this' FROM t -- :comment\nWHERE y = :real")).toEqual(["real"]);
expect(detectSqlParams("/* :hidden */ SELECT :shown")).toEqual(["shown"]);
});
it("is empty for a template without parameters", () => {
expect(detectSqlParams("SELECT 1")).toEqual([]);
});
});
describe("sqlParamStatus", () => {
it("separates undeclared and unused names", () => {
const status = sqlParamStatus("SELECT :a, :b", ["a", " c ", ""]);
expect(status.used).toEqual(["a", "b"]);
expect(status.undeclared).toEqual(["b"]);
expect(status.unused).toEqual(["c"]);
});
});
describe("value text", () => {
it("blank text always fits (no default / not provided)", () => {
for (const type of ["string", "integer", "number", "boolean", "datetime"]) {
expect(isValueTextValid(type, " ")).toBe(true);
}
});
it("checks integer, number and boolean text", () => {
expect(isValueTextValid("integer", "42")).toBe(true);
expect(isValueTextValid("integer", "4.2")).toBe(false);
expect(isValueTextValid("integer", "abc")).toBe(false);
expect(isValueTextValid("number", "4.2")).toBe(true);
expect(isValueTextValid("number", "abc")).toBe(false);
expect(isValueTextValid("boolean", "true")).toBe(true);
expect(isValueTextValid("boolean", "yes")).toBe(false);
expect(isValueTextValid("datetime", "2026-11-17 00:00:00")).toBe(true);
});
it("converts text to JSON values by type", () => {
expect(parseValueText("integer", " 7 ")).toBe(7);
expect(parseValueText("number", "0.5")).toBe(0.5);
expect(parseValueText("boolean", "false")).toBe(false);
expect(parseValueText("boolean", "true")).toBe(true);
expect(parseValueText("string", " keep spaces ")).toBe(" keep spaces ");
expect(parseValueText("datetime", " 2026-11-17 ")).toBe("2026-11-17");
});
});
describe("firstParamIssue", () => {
it("accepts a clean list", () => {
expect(firstParamIssue([param(), param({ key: 2, name: "since", type: "datetime" })])).toBeNull();
});
it("flags a bad name, a duplicate and a default that does not fit", () => {
expect(firstParamIssue([param({ name: "1bad" })])).toEqual({ issue: "invalidName", name: "1bad" });
expect(firstParamIssue([param({ name: " " })])).toEqual({ issue: "invalidName", name: "" });
expect(firstParamIssue([param(), param({ key: 2 })])).toEqual({ issue: "duplicate", name: "line_code" });
expect(firstParamIssue([param({ type: "integer", defaultText: "x" })])).toEqual({
issue: "invalidDefault",
name: "line_code",
});
});
});
describe("firstOutputIssue", () => {
it("accepts a clean list and an empty one", () => {
expect(firstOutputIssue([])).toBeNull();
expect(firstOutputIssue([output(), output({ key: 2, name: "temperature", type: "number" })])).toBeNull();
});
it("flags blank, too long and duplicate names", () => {
expect(firstOutputIssue([output({ name: " " })])).toEqual({ issue: "invalidName", name: "" });
expect(firstOutputIssue([output({ name: "x".repeat(129) })])?.issue).toBe("invalidName");
expect(firstOutputIssue([output(), output({ key: 2 })])).toEqual({ issue: "duplicate", name: "lot_no" });
});
});
+123
View File
@@ -0,0 +1,123 @@
/**
* Pure checks behind the query form, so they can be unit tested without a DOM.
* Boundary: these mirror the backend's schema rules for early feedback only; the server stays
* the authority. SQL is never parsed beyond spotting `:name` markers for a hint.
*/
import { MAX_OUTPUT_NAME, type OutputRow, type ParamRow } from "./types";
/** Same pattern the backend uses for parameter names and allowed identifiers. */
const IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
export function isFilledText(value: unknown): boolean {
return typeof value === "string" && value.trim() !== "";
}
/** A whole number within [min, max]. null, NaN, decimals and strings are rejected. */
export function isIntegerInRange(value: unknown, min: number, max: number): boolean {
return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
}
export function isValidIdentifier(value: string): boolean {
return IDENTIFIER_RE.test(value);
}
/**
* Parameter names used in a template as `:name`. Quoted text, comments and `::` casts are
* skipped, so this is a hint only (the server prepares the real statement).
*/
export function detectSqlParams(sql: string): string[] {
const text = sql
.replace(/\/\*[\s\S]*?\*\//g, " ")
.replace(/--[^\n]*/g, " ")
.replace(/'(?:[^']|'')*'/g, "''");
const found: string[] = [];
const pattern = /(^|[^:\w]):([A-Za-z_]\w*)/g;
let match = pattern.exec(text);
while (match) {
if (!found.includes(match[2])) {
found.push(match[2]);
}
match = pattern.exec(text);
}
return found;
}
export type SqlParamStatus = { used: string[]; undeclared: string[]; unused: string[] };
export function sqlParamStatus(sql: string, declared: string[]): SqlParamStatus {
const used = detectSqlParams(sql);
const names = declared.map((name) => name.trim()).filter((name) => name !== "");
return {
used,
undeclared: used.filter((name) => !names.includes(name)),
unused: names.filter((name) => !used.includes(name)),
};
}
/** Whether a typed default or preview value text fits the declared type. Blank means "none". */
export function isValueTextValid(type: string, text: string): boolean {
const value = text.trim();
if (value === "") {
return true;
}
if (type === "integer") {
return /^[+-]?\d+$/.test(value);
}
if (type === "number") {
return Number.isFinite(Number(value));
}
if (type === "boolean") {
return value === "true" || value === "false";
}
// string and datetime: any text; the server judges a datetime's format.
return true;
}
/** Converts a value text to a JSON value of the declared type. Call only when valid. */
export function parseValueText(type: string, text: string): string | number | boolean {
if (type === "integer" || type === "number") {
return Number(text.trim());
}
if (type === "boolean") {
return text.trim() === "true";
}
return type === "datetime" ? text.trim() : text;
}
export type RowIssue = "invalidName" | "duplicate" | "invalidDefault";
/** First problem in the parameter rows, with the offending name, or null. */
export function firstParamIssue(rows: ParamRow[]): { issue: RowIssue; name: string } | null {
const seen = new Set<string>();
for (const row of rows) {
const name = row.name.trim();
if (!isValidIdentifier(name)) {
return { issue: "invalidName", name };
}
if (seen.has(name)) {
return { issue: "duplicate", name };
}
seen.add(name);
if (!isValueTextValid(row.type, row.defaultText)) {
return { issue: "invalidDefault", name };
}
}
return null;
}
/** First problem in the output rows, with the offending name, or null. */
export function firstOutputIssue(rows: OutputRow[]): { issue: RowIssue; name: string } | null {
const seen = new Set<string>();
for (const row of rows) {
const name = row.name.trim();
if (name === "" || name.length > MAX_OUTPUT_NAME) {
return { issue: "invalidName", name };
}
if (seen.has(name)) {
return { issue: "duplicate", name };
}
seen.add(name);
}
return null;
}
+36 -2
View File
@@ -1,7 +1,7 @@
/**
* Console routes. Hash history keeps every page URL out of the API proxy prefixes
* (the datasource API also lives under /datasources).
* `meta.crumbs` lists the nav keys after "Watchman" in the breadcrumb.
* (the datasource and query APIs also live under /datasources and /queries).
* `meta.crumbs` lists the nav keys after the app name crumb in the breadcrumb.
*/
import { createRouter, createWebHashHistory, type RouterHistory } from "vue-router";
@@ -9,6 +9,10 @@ import DatasourceEdit from "./datasources/DatasourceEdit.vue";
import DatasourceGate from "./datasources/DatasourceGate.vue";
import DatasourceList from "./datasources/DatasourceList.vue";
import HomeView from "./HomeView.vue";
import QueryEdit from "./queries/QueryEdit.vue";
import QueryGate from "./queries/QueryGate.vue";
import QueryList from "./queries/QueryList.vue";
import QueryVersionView from "./queries/QueryVersionView.vue";
export function createAppRouter(history: RouterHistory = createWebHashHistory()) {
return createRouter({
@@ -39,6 +43,36 @@ export function createAppRouter(history: RouterHistory = createWebHashHistory())
},
],
},
{
path: "/queries",
component: QueryGate,
children: [
{
path: "",
name: "query-list",
component: QueryList,
meta: { crumbs: ["queries"] },
},
{
path: "new",
name: "query-create",
component: QueryEdit,
meta: { crumbs: ["queries", "create"] },
},
{
path: ":id",
name: "query-detail",
component: QueryEdit,
meta: { crumbs: ["queries", "detail"] },
},
{
path: ":id/versions/:versionNo",
name: "query-version",
component: QueryVersionView,
meta: { crumbs: ["queries", "detail", "version"] },
},
],
},
{ path: "/:pathMatch(.*)*", redirect: "/" },
],
});
+10 -1
View File
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it } from "vitest";
import { allowsDatasources, authHeaders, clearSession, loadSession, saveSession } from "./session";
import { allowsDatasources, allowsQueries, authHeaders, clearSession, loadSession, saveSession } from "./session";
describe("session token storage", () => {
beforeEach(() => {
@@ -31,3 +31,12 @@ describe("datasource access", () => {
expect(allowsDatasources([])).toBe(false);
});
});
describe("query access", () => {
it("allows only watchman-admin, like datasources", () => {
expect(allowsQueries(["watchman-admin"])).toBe(true);
expect(allowsQueries(["watchman-operator"])).toBe(false);
expect(allowsQueries(["watchman-viewer"])).toBe(false);
expect(allowsQueries([])).toBe(false);
});
});
+5
View File
@@ -23,6 +23,11 @@ export function allowsDatasources(roles: string[]): boolean {
return roles.includes("watchman-admin");
}
/** Only watchman-admin opens the query pages (same rule as datasources). */
export function allowsQueries(roles: string[]): boolean {
return roles.includes("watchman-admin");
}
export function saveSession(user: SessionUser): void {
const next = { ...user };
if (next.expires_in && !next.token_expires_at) {
+23
View File
@@ -0,0 +1,23 @@
/**
* Shared console table layout helpers.
* Action-column widths are fixed by link-button count (see docs/current/frontend-ui.md).
*/
/** ~48px per link button + 24px padding; keeps the ops column from stretching. */
const ACTIONS_WIDTH_BY_COUNT: Record<number, number> = {
1: 72,
2: 120,
3: 168,
4: 216,
5: 264,
};
export function actionsColumnWidth(buttonCount: number): number {
if (buttonCount in ACTIONS_WIDTH_BY_COUNT) {
return ACTIONS_WIDTH_BY_COUNT[buttonCount];
}
return Math.max(72, 24 + buttonCount * 48);
}
export const LIST_PAGE_SIZES = [10, 20, 50] as const;
export const LIST_DEFAULT_PAGE_SIZE = 20;
+1
View File
@@ -12,6 +12,7 @@ export default defineConfig({
"/platform": "http://127.0.0.1:8000",
"/auth": "http://127.0.0.1:8000",
"/datasources": "http://127.0.0.1:8000",
"/queries": "http://127.0.0.1:8000",
},
},
});