@h-ai/cli 0.1.0-alpha.54 → 0.1.0-alpha.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +4 -0
  2. package/package.json +7 -7
  3. package/templates/base/package.json.hbs +1 -1
  4. package/templates/skills/AGENTS.md +8 -22
  5. package/templates/skills/CLAUDE.md +3 -16
  6. package/templates/skills/bridges/admin/AGENTS.md +3 -16
  7. package/templates/skills/bridges/admin/CLAUDE.md +3 -11
  8. package/templates/skills/bridges/admin/copilot-instructions.md +2 -39
  9. package/templates/skills/bridges/api/AGENTS.md +5 -18
  10. package/templates/skills/bridges/api/CLAUDE.md +3 -11
  11. package/templates/skills/bridges/api/copilot-instructions.md +3 -38
  12. package/templates/skills/bridges/fullstack/AGENTS.md.hbs +24 -59
  13. package/templates/skills/bridges/fullstack/CLAUDE.md.hbs +1 -15
  14. package/templates/skills/bridges/fullstack/copilot-instructions.md.hbs +5 -45
  15. package/templates/skills/bridges/h5/AGENTS.md +4 -17
  16. package/templates/skills/bridges/h5/CLAUDE.md +3 -11
  17. package/templates/skills/bridges/h5/copilot-instructions.md +2 -37
  18. package/templates/skills/bridges/mobile-app/AGENTS.md +5 -18
  19. package/templates/skills/bridges/mobile-app/CLAUDE.md +3 -11
  20. package/templates/skills/bridges/mobile-app/copilot-instructions.md +2 -38
  21. package/templates/skills/bridges/website/AGENTS.md +4 -17
  22. package/templates/skills/bridges/website/CLAUDE.md +3 -11
  23. package/templates/skills/bridges/website/copilot-instructions.md +2 -37
  24. package/templates/skills/copilot-instructions.md +2 -36
  25. package/templates/skills/hai-ai/SKILL.md +35 -389
  26. package/templates/skills/hai-ai/guide.md +383 -0
  27. package/templates/skills/hai-ai/reference.md +1 -1
  28. package/templates/skills/hai-api-client/SKILL.md +6 -6
  29. package/templates/skills/hai-api-contract/SKILL.md +10 -25
  30. package/templates/skills/hai-app-create/SKILL.md +29 -388
  31. package/templates/skills/hai-app-create/reference.md +350 -0
  32. package/templates/skills/hai-app-review/SKILL.md +9 -23
  33. package/templates/skills/hai-app-tests/SKILL.md +29 -494
  34. package/templates/skills/hai-app-tests/reference.md +442 -0
  35. package/templates/skills/hai-audit/SKILL.md +6 -6
  36. package/templates/skills/hai-build/SKILL.md +19 -338
  37. package/templates/skills/hai-build/reference.md +326 -0
  38. package/templates/skills/hai-cache/SKILL.md +27 -32
  39. package/templates/skills/hai-capacitor/SKILL.md +19 -366
  40. package/templates/skills/hai-capacitor/reference.md +352 -0
  41. package/templates/skills/hai-ci/SKILL.md +6 -21
  42. package/templates/skills/hai-core/SKILL.md +25 -566
  43. package/templates/skills/hai-core/reference.md +533 -0
  44. package/templates/skills/hai-crypto/SKILL.md +6 -20
  45. package/templates/skills/hai-datapipe/SKILL.md +9 -23
  46. package/templates/skills/hai-deploy/SKILL.md +6 -24
  47. package/templates/skills/hai-framework-sync/SKILL.md +8 -20
  48. package/templates/skills/hai-iam/SKILL.md +27 -371
  49. package/templates/skills/hai-iam/reference.md +343 -0
  50. package/templates/skills/hai-kit/SKILL.md +6 -6
  51. package/templates/skills/hai-payment/SKILL.md +6 -26
  52. package/templates/skills/hai-pr-review/SKILL.md +6 -22
  53. package/templates/skills/hai-reach/SKILL.md +19 -317
  54. package/templates/skills/hai-reach/reference.md +303 -0
  55. package/templates/skills/hai-reldb/SKILL.md +19 -472
  56. package/templates/skills/hai-reldb/reference.md +452 -0
  57. package/templates/skills/hai-scheduler/SKILL.md +6 -6
  58. package/templates/skills/hai-serv/SKILL.md +27 -759
  59. package/templates/skills/hai-serv/reference.md +736 -0
  60. package/templates/skills/hai-storage/SKILL.md +7 -25
  61. package/templates/skills/hai-ui/SKILL.md +29 -625
  62. package/templates/skills/hai-ui/reference.md +598 -0
  63. package/templates/skills/hai-vecdb/SKILL.md +18 -303
  64. package/templates/skills/hai-vecdb/reference.md +291 -0
@@ -0,0 +1,452 @@
1
+ # hai-reldb — 详细用法
2
+
3
+ 从 [SKILL.md](SKILL.md) 选择主题后读取对应小节。代码片段展示 API 用法;省略的业务变量、schema、依赖与 return 上下文需由应用补齐。
4
+
5
+ > `@h-ai/reldb` 提供统一的数据库操作接口,支持 SQLite、PostgreSQL、MySQL,包含 DDL、SQL、CRUD 抽象、事务与分页。
6
+
7
+ ## 运行环境
8
+
9
+ > ⚠️ **服务端模块(Node.js only)。** 浏览器端请通过 `@h-ai/api-contract` + `@h-ai/serv` 暴露的 API 端点间接访问数据库。
10
+
11
+ ## 适用场景
12
+
13
+ - 新增或修改数据库访问逻辑(SQL/DDL/CRUD/事务)
14
+ - 使用 `reldb.crud.table` 或 `BaseReldbCrudRepository` 构建数据仓库
15
+ - 处理分页查询与分页结果规范化
16
+ - 基于 `HaiReldbError` 做错误分支处理
17
+ - JSON 列的路径提取、设置、插入、删除、合并操作(跨数据库统一语法)
18
+
19
+ ## 使用步骤
20
+
21
+ ### 1. 配置
22
+
23
+ ```yaml
24
+ # config/_db.yml
25
+ type: sqlite
26
+ database: ./data/app.db
27
+ # PostgreSQL/MySQL 额外字段:
28
+ # host: localhost
29
+ # port: 5432
30
+ # user: postgres
31
+ # password: ''
32
+ operationLog:
33
+ read: false # query / get / queryPage
34
+ write: false # DDL, execute / batch, tx.begin / tx.commit / tx.rollback
35
+ maxLength: 1000
36
+ level: debug # info | debug | trace
37
+ ```
38
+
39
+ 约定环境变量优先于 YAML,例如 `HAI_DB_TYPE`、`HAI_DB_DATABASE`、
40
+ `HAI_DB_OPERATIONLOG_LEVEL`。
41
+
42
+ `operationLog` 在 reldb provider-base 的 DML 操作层统一输出日志,不要在 `reldb-main.ts`、各 raw provider 或调用方重复包装。`read` 覆盖 `query/get/queryPage`,`write` 覆盖 DDL、`execute/batch` 与 `tx.begin/commit/rollback`,`maxLength` 用于截断序列化后的 SQL 参数和批量语句,`level` 默认 `debug`。
43
+
44
+ ### 2. 初始化与关闭
45
+
46
+ ```typescript
47
+ import { core } from '@h-ai/core'
48
+ import { reldb } from '@h-ai/reldb'
49
+
50
+ await reldb.init(core.config.get('db'))
51
+ // ... 使用数据库
52
+ await reldb.close()
53
+ ```
54
+
55
+ `reldb.config` 返回的是脱敏后的配置快照;数据库密码与 URL 内嵌凭证会自动隐藏。
56
+
57
+ ### 3. 选择操作接口
58
+
59
+ | 接口 | 用途 | 入口 |
60
+ | ---- | ------------------ | ---------------------------- |
61
+ | DDL | 建表/索引/字段变更 | `reldb.ddl` |
62
+ | SQL | 原始查询/执行/分页 | `reldb.sql` |
63
+ | CRUD | 通用增删改查 | `reldb.crud.table(config)` |
64
+ | 仓库 | 业务数据仓库封装 | `extends BaseReldbCrudRepository` |
65
+ | 事务 | 事务管理 | `reldb.tx` |
66
+ | 分页 | 分页参数与结果 | `reldb.pagination` |
67
+ | JSON | JSON 路径操作 | `reldb.json` |
68
+
69
+ ## 核心 API
70
+
71
+ 事务边界:`tx.wrap` 对正常返回值一律提交,不识别失败 HaiResult;回调内检查每步结果,失败抛错以触发回滚(外层返回 TRANSACTION_FAILED)。需保留原错误码时使用手动事务。
72
+
73
+ ### DDL — `reldb.ddl`
74
+
75
+ | 方法 | 签名 | 说明 |
76
+ | ------------- | ----------------------------------------------------------------------- | -------------------------- |
77
+ | `createTable` | `(tableName, columns: ReldbTableDef, ifNotExists?: boolean) => HaiResult<void>` | 建表(默认 IF NOT EXISTS) |
78
+ | `dropTable` | `(tableName, ifExists?: boolean) => HaiResult<void>` | 删除表(默认 IF EXISTS) |
79
+ | `addColumn` | `(tableName, columnName, columnDef: ReldbColumnDef) => HaiResult<void>` | 添加列 |
80
+ | `dropColumn` | `(tableName, columnName) => HaiResult<void>` | 删除列 |
81
+ | `renameTable` | `(oldName, newName) => HaiResult<void>` | 重命名表 |
82
+ | `createIndex` | `(tableName, indexName, indexDef: ReldbIndexDef) => HaiResult<void>` | 创建索引 |
83
+ | `dropIndex` | `(indexName, ifExists?: boolean) => HaiResult<void>` | 删除索引 |
84
+ | `raw` | `(sql: string) => HaiResult<void>` | 执行原始 DDL |
85
+
86
+ > 所有方法均返回 `Promise<HaiResult<void>>`,上表省略异步与错误类型。
87
+
88
+ **ReldbTableDef**(列名到列定义的映射):
89
+
90
+ ```typescript
91
+ const columns: ReldbTableDef = {
92
+ id: { type: 'INTEGER', primaryKey: true, autoIncrement: true },
93
+ name: { type: 'TEXT', notNull: true },
94
+ email: { type: 'TEXT', unique: true },
95
+ score: { type: 'REAL', defaultValue: 0 },
96
+ active: { type: 'BOOLEAN' },
97
+ metadata: { type: 'JSON' },
98
+ created_at: { type: 'TIMESTAMP' },
99
+ }
100
+ ```
101
+
102
+ **ReldbColumnDef**(列类型与约束):
103
+
104
+ ```typescript
105
+ interface ReldbColumnDef {
106
+ type: 'TEXT' | 'INTEGER' | 'REAL' | 'BLOB' | 'BOOLEAN' | 'TIMESTAMP' | 'JSON'
107
+ primaryKey?: boolean
108
+ autoIncrement?: boolean
109
+ notNull?: boolean
110
+ unique?: boolean
111
+ defaultValue?: string | number | boolean | null
112
+ references?: { table: string, column: string, onDelete?: 'CASCADE' | 'SET NULL' | 'RESTRICT' | 'NO ACTION', onUpdate?: '...' }
113
+ }
114
+ ```
115
+
116
+ **跨数据库类型映射**:
117
+
118
+ | 类型 | SQLite | PostgreSQL | MySQL |
119
+ | --------- | ------- | ---------------- | ------------ |
120
+ | TEXT | TEXT | TEXT | VARCHAR(255) |
121
+ | INTEGER | INTEGER | INTEGER/SERIAL | INT/BIGINT |
122
+ | REAL | REAL | DOUBLE PRECISION | DOUBLE |
123
+ | BLOB | BLOB | BYTEA | BLOB |
124
+ | BOOLEAN | INTEGER | BOOLEAN | TINYINT(1) |
125
+ | TIMESTAMP | INTEGER | TIMESTAMP | DATETIME |
126
+ | JSON | TEXT | JSONB | JSON |
127
+
128
+ > MySQL 将 TEXT 映射为 VARCHAR(255) 以支持索引和 UNIQUE 约束。INTEGER + autoIncrement 在 MySQL 映射为 BIGINT。
129
+
130
+ ### SQL — `reldb.sql`
131
+
132
+ | 方法 | 签名 | 说明 |
133
+ | ----------- | ----------------------------------------------------------------- | ------------ |
134
+ | `query` | `<T>(sql, params?) => HaiResult<T[]>` | 查询返回多行 |
135
+ | `get` | `<T>(sql, params?) => HaiResult<T \| null>` | 查询返回单行 |
136
+ | `execute` | `(sql, params?) => HaiResult<ExecuteResult>` | 执行写操作 |
137
+ | `batch` | `(statements: Array<{ sql, params? }>) => HaiResult<void>` | 批量执行 |
138
+ | `queryPage` | `<T>(options: PaginationQueryOptions) => HaiResult<PaginatedResult>` | 分页查询 |
139
+
140
+ > 所有方法均返回 `Promise<HaiResult<T>>`,上表省略异步与错误类型。
141
+
142
+ **参数占位符统一使用 `?`**(PostgreSQL 的 `$n` 由 Provider 自动转换):
143
+
144
+ ```typescript
145
+ const result = await reldb.sql.query<User>(
146
+ 'SELECT * FROM users WHERE status = ? AND age > ?',
147
+ ['active', 18],
148
+ )
149
+ ```
150
+
151
+ **ExecuteResult**:
152
+
153
+ ```typescript
154
+ interface ExecuteResult {
155
+ changes: number // 影响的行数
156
+ lastInsertRowid?: number | bigint // INSERT 时生效(PostgreSQL 不返回此字段)
157
+ }
158
+ ```
159
+
160
+ **分页查询**:
161
+
162
+ ```typescript
163
+ const page = await reldb.sql.queryPage<User>({
164
+ sql: 'SELECT * FROM users WHERE status = ? ORDER BY id',
165
+ params: ['active'],
166
+ pagination: { page: 1, pageSize: 20 },
167
+ overrides: { maxPageSize: 100 }, // 可选:限制最大页大小
168
+ })
169
+ // page.data => { items, total, page, pageSize }
170
+ ```
171
+
172
+ ### CRUD — `reldb.crud.table(config)`
173
+
174
+ 通过配置创建单表 CRUD 仓库,免写 SQL:
175
+
176
+ ```typescript
177
+ const userCrud = reldb.crud.table<{ id: number, name: string, email: string }>({
178
+ table: 'users',
179
+ idColumn: 'id', // 主键列,默认 'id'
180
+ select: ['id', 'name', 'email'], // 查询列,默认 '*'
181
+ createColumns: ['name', 'email'], // 允许插入的列
182
+ updateColumns: ['name', 'email'], // 允许更新的列
183
+ })
184
+ ```
185
+
186
+ 返回的 ReldbCrudRepository 方法:
187
+
188
+ | 方法 | 签名 | 说明 |
189
+ | ------------ | ---------------------------------------------- | ------------ |
190
+ | `create` | `(data, tx?) => HaiResult<ExecuteResult>` | 创建单条 |
191
+ | `createMany` | `(items, tx?) => HaiResult<void>` | 批量创建 |
192
+ | `findById` | `(id, tx?) => HaiResult<T \| null>` | 按 ID 查询 |
193
+ | `findAll` | `(options?, tx?) => HaiResult<T[]>` | 条件查询 |
194
+ | `findPage` | `(options, tx?) => HaiResult<PaginatedResult<T>>` | 分页查询 |
195
+ | `updateById` | `(id, data, tx?) => HaiResult<ExecuteResult>` | 按 ID 更新 |
196
+ | `deleteById` | `(id, tx?) => HaiResult<ExecuteResult>` | 按 ID 删除 |
197
+ | `count` | `(options?, tx?) => HaiResult<number>` | 计数 |
198
+ | `exists` | `(options?, tx?) => HaiResult<boolean>` | 条件是否存在 |
199
+ | `existsById` | `(id, tx?) => HaiResult<boolean>` | ID 是否存在 |
200
+
201
+ > 所有方法均支持可选 `tx` 事务参数。`create`/`updateById` 中的 `data` 会根据 `createColumns`/`updateColumns` 白名单过滤列。
202
+
203
+ **使用示例**:
204
+
205
+ ```typescript
206
+ // 单条插入
207
+ const result = await userCrud.create({ name: '张三', email: 'test@example.com' })
208
+ // result.data → { changes: 1, lastInsertRowid: 1 }
209
+
210
+ // 批量插入
211
+ await userCrud.createMany([
212
+ { name: '用户A', email: 'a@test.com' },
213
+ { name: '用户B', email: 'b@test.com' },
214
+ ])
215
+
216
+ // 主键查找
217
+ const user = await userCrud.findById(1)
218
+ // user.data → { id: 1, name: '张三', email: 'test@example.com' } | null
219
+
220
+ // 条件查询(where + params 占位符)
221
+ const actives = await userCrud.findAll({
222
+ where: 'name LIKE ?',
223
+ params: ['%张%'],
224
+ orderBy: 'id DESC',
225
+ limit: 10,
226
+ offset: 0,
227
+ })
228
+
229
+ // 分页查询
230
+ const page = await userCrud.findPage({
231
+ where: 'name LIKE ?',
232
+ params: ['%张%'],
233
+ orderBy: 'id DESC',
234
+ pagination: { page: 1, pageSize: 20 },
235
+ })
236
+ // page.data → { items: [...], total: 100, page: 1, pageSize: 20 }
237
+
238
+ // 更新 / 删除
239
+ await userCrud.updateById(1, { name: '新名字' })
240
+ await userCrud.deleteById(1)
241
+
242
+ // 计数 / 存在性
243
+ const total = await userCrud.count({ where: 'name LIKE ?', params: ['%张%'] })
244
+ const has = await userCrud.exists({ where: 'email = ?', params: ['test@example.com'] })
245
+ const found = await userCrud.existsById(1)
246
+
247
+ // 事务中使用(所有方法均支持 tx 参数)
248
+ await reldb.tx.wrap(async (tx) => {
249
+ const created = await userCrud.create({ name: '用户A', email: 'a@test.com' }, tx)
250
+ if (!created.success) throw new Error(created.error.message)
251
+ const updated = await userCrud.updateById(1, { name: '新名字' }, tx)
252
+ if (!updated.success) throw new Error(updated.error.message)
253
+ const user = await userCrud.findById(1, tx)
254
+ if (!user.success) throw new Error(user.error.message)
255
+ return user.data
256
+ })
257
+ ```
258
+
259
+ ### BaseReldbCrudRepository
260
+
261
+ 业务仓库基类,提供字段映射、自动建表与类型转换能力:
262
+
263
+ ```typescript
264
+ import { BaseReldbCrudRepository } from '@h-ai/reldb'
265
+
266
+ interface User { id: number, name: string, email: string, createdAt: Date, updatedAt: Date }
267
+
268
+ class UserRepository extends BaseReldbCrudRepository<User> {
269
+ constructor() {
270
+ super(db, {
271
+ table: 'users',
272
+ idColumn: 'id',
273
+ fields: [
274
+ { fieldName: 'id', columnName: 'id', def: { type: 'INTEGER', primaryKey: true, autoIncrement: true }, select: true, create: false, update: false },
275
+ { fieldName: 'name', columnName: 'name', def: { type: 'TEXT', notNull: true }, select: true, create: true, update: true },
276
+ { fieldName: 'email', columnName: 'email', def: { type: 'TEXT', notNull: true }, select: true, create: true, update: true },
277
+ { fieldName: 'createdAt', columnName: 'created_at', def: { type: 'TIMESTAMP', notNull: true }, select: true, create: true, update: false },
278
+ { fieldName: 'updatedAt', columnName: 'updated_at', def: { type: 'TIMESTAMP', notNull: true }, select: true, create: true, update: false },
279
+ ],
280
+ })
281
+ }
282
+
283
+ /** 自定义查询示例 */
284
+ async findByEmail(email: string, tx?: DmlWithTxOperations) {
285
+ return this.sql(tx).get<User>('SELECT * FROM users WHERE email = ?', [email])
286
+ }
287
+ }
288
+ ```
289
+
290
+ **`this.sql(tx?)`**:返回 `DmlOperations`(`reldb.sql` 或传入的事务句柄),自动适配事务场景。
291
+
292
+ **自动能力**:
293
+
294
+ - `createdAt` / `updatedAt` 字段自动填充时间戳
295
+ - 主键生成(非 autoIncrement 主键默认使用随机 UUID,底层带安全上下文守卫,不可用时回退;业务侧手动生成 UUID 一律用 `core.id.uuid()`)
296
+ - BOOLEAN → 1/0(SQLite/MySQL)或 true/false(PostgreSQL)
297
+ - TIMESTAMP → 毫秒时间戳(SQLite)或 Date(PG/MySQL)
298
+ - JSON → 字符串序列化(SQLite/MySQL)或原生 JSONB(PG)
299
+
300
+ ### 事务 — `reldb.tx`
301
+
302
+ ```typescript
303
+ // 方式1:wrap(自动 commit/rollback)
304
+ const result = await reldb.tx.wrap(async (tx) => {
305
+ const inserted = await tx.execute('INSERT INTO users (name) VALUES (?)', ['张三'])
306
+ if (!inserted.success) throw new Error(inserted.error.message)
307
+ const logged = await tx.execute('INSERT INTO logs (action) VALUES (?)', ['user_created'])
308
+ if (!logged.success) throw new Error(logged.error.message)
309
+ return 'done'
310
+ })
311
+ // result.data === 'done'(正常返回自动 commit)
312
+ // 回调抛异常 → 自动 rollback → result.success === false
313
+
314
+ // 方式2:手动管理,保留原领域错误(置于 async 函数内)
315
+ const txResult = await reldb.tx.begin()
316
+ if (!txResult.success) return txResult
317
+ const tx = txResult.data
318
+ const inserted = await tx.execute('INSERT INTO users (name) VALUES (?)', ['李四'])
319
+ if (!inserted.success) {
320
+ const rollback = await tx.rollback()
321
+ if (!rollback.success) return rollback
322
+ return inserted
323
+ }
324
+ return tx.commit()
325
+ ```
326
+
327
+ **事务内可用操作**:
328
+
329
+ - `tx.query / tx.get / tx.execute / tx.batch / tx.queryPage`
330
+ - `tx.crud.table(config)` — 事务内的 CRUD 仓库
331
+ - `tx.commit() / tx.rollback()`
332
+
333
+ ### 分页 — `reldb.pagination`
334
+
335
+ | 方法 | 签名 | 说明 |
336
+ | ----------- | ----------------------------------------------------- | -------------------------------------- |
337
+ | `normalize` | `(options?, overrides?) => NormalizedPagination` | 规范化分页参数(含 offset/limit 计算) |
338
+ | `build` | `<T>(items, total, pagination) => PaginatedResult<T>` | 构建分页结果对象 |
339
+
340
+ ```typescript
341
+ // PaginatedResult 结构
342
+ interface PaginatedResult<T> {
343
+ items: T[]
344
+ total: number
345
+ page: number
346
+ pageSize: number
347
+ }
348
+
349
+ // 默认值:page=1, pageSize=20, maxPageSize=200
350
+ ```
351
+
352
+ ### JSON — `reldb.json`
353
+
354
+ 通过 `reldb.json` 构建跨数据库统一的 JSON 路径操作 SQL 表达式,返回 `{ sql, params }` 可直接嵌入 `reldb.sql.*`。
355
+
356
+ 路径格式遵循 SQL/JSON Path 标准,以 `$` 开头(如 `$.key`、`$.key.subkey`、`$[0]`)。
357
+
358
+ | 操作 | SQLite | PostgreSQL | MySQL |
359
+ | --------- | ------------------ | ------------------------ | ---------------------- |
360
+ | `extract` | `json_extract` | `#>` (text[]) | `JSON_EXTRACT` |
361
+ | `set` | `json_set` | `jsonb_set` | `JSON_SET` |
362
+ | `insert` | `json_insert` | `jsonb_insert` | `JSON_INSERT` |
363
+ | `remove` | `json_remove` | `#-` (text[]) | `JSON_REMOVE` |
364
+ | `merge` | `json_patch` | `|| ::jsonb` | `JSON_MERGE_PATCH` |
365
+
366
+ ```typescript
367
+ // 提取 JSON 字段值(用于 WHERE 条件)
368
+ const { sql, params } = reldb.json.extract('settings', '$.theme')
369
+ const rows = await reldb.sql.query(
370
+ `SELECT * FROM users WHERE ${sql} = ?`,
371
+ [...params, '"dark"'],
372
+ )
373
+
374
+ // 设置 JSON 字段路径(创建或替换)
375
+ const { sql, params } = reldb.json.set('settings', '$.theme', 'dark')
376
+ await reldb.sql.execute(
377
+ `UPDATE users SET settings = ${sql} WHERE id = ?`,
378
+ [...params, userId],
379
+ )
380
+
381
+ // 删除 JSON 字段路径
382
+ const { sql, params } = reldb.json.remove('settings', '$.deprecated')
383
+ await reldb.sql.execute(`UPDATE users SET settings = ${sql} WHERE id = ?`, [...params, id])
384
+
385
+ // 合并 JSON 对象(RFC 7396:null 值表示删除对应键)
386
+ const { sql, params } = reldb.json.merge('profile', { bio: '新简介', avatar: null })
387
+ await reldb.sql.execute(`UPDATE users SET profile = ${sql} WHERE id = ?`, [...params, userId])
388
+ ```
389
+
390
+ > `column` 参数为列名,**禁止传入用户输入**(开发者负责安全性)。
391
+
392
+ ## 错误码 — `HaiReldbError`
393
+
394
+ | 错误码 | code | 说明 |
395
+ |--------|------|------|
396
+ | `HaiReldbError.CONNECTION_FAILED` | `hai:reldb:001` | 数据库连接失败 |
397
+ | `HaiReldbError.QUERY_FAILED` | `hai:reldb:002` | 查询或执行失败 |
398
+ | `HaiReldbError.CONSTRAINT_VIOLATION` | `hai:reldb:003` | 约束违反 |
399
+ | `HaiReldbError.TRANSACTION_FAILED` | `hai:reldb:004` | 事务失败 |
400
+ | `HaiReldbError.MIGRATION_FAILED` | `hai:reldb:005` | 迁移失败 |
401
+ | `HaiReldbError.RECORD_NOT_FOUND` | `hai:reldb:006` | 记录不存在 |
402
+ | `HaiReldbError.DUPLICATE_ENTRY` | `hai:reldb:007` | 重复条目 |
403
+ | `HaiReldbError.DEADLOCK` | `hai:reldb:008` | 死锁 |
404
+ | `HaiReldbError.TIMEOUT` | `hai:reldb:009` | 超时 |
405
+ | `HaiReldbError.NOT_INITIALIZED` | `hai:reldb:010` | 数据库未初始化 |
406
+ | `HaiReldbError.POOL_EXHAUSTED` | `hai:reldb:011` | 连接池耗尽 |
407
+ | `HaiReldbError.UNSUPPORTED_TYPE` | `hai:reldb:012` | 不支持的数据库类型 |
408
+ | `HaiReldbError.CONFIG_ERROR` | `hai:reldb:013` | 配置错误 |
409
+ | `HaiReldbError.DDL_FAILED` | `hai:reldb:020` | DDL 操作失败 |
410
+
411
+ ## 常见模式
412
+
413
+ ### API 端点中使用
414
+
415
+ ```typescript
416
+ import { reldb, HaiReldbError } from '@h-ai/reldb'
417
+ import { kit } from '@h-ai/kit'
418
+
419
+ export const GET = kit.handler(async ({ url }) => {
420
+ // query 返回校验后的数据,失败抛 Response,由 kit.handler 处理。
421
+ const pagination = kit.validate.query(url, PageSchema)
422
+ const result = await userCrud.findPage({ pagination, orderBy: 'id ASC' })
423
+ if (!result.success)
424
+ return kit.response.error(result.error.code, result.error.message)
425
+ return kit.response.ok(result.data)
426
+ })
427
+ ```
428
+
429
+ ### 事务跨仓库
430
+
431
+ ```typescript
432
+ const result = await reldb.tx.wrap(async (tx) => {
433
+ const user = await userRepo.create(userData, tx)
434
+ if (!user.success)
435
+ throw new Error(user.error.message)
436
+
437
+ const profile = await profileRepo.create({ userId: user.data.lastInsertRowid, ...profileData }, tx)
438
+ if (!profile.success) throw new Error(profile.error.message)
439
+ return user.data
440
+ })
441
+ ```
442
+
443
+ ### BaseReldbCrudRepository 事务集成
444
+
445
+ 与上述事务相同:每个 Repository 方法传入同一 tx,并检查每次 HaiResult;失败 rollback,全部成功后 commit。不要只等待 Promise 完成就提交。
446
+
447
+ ## 相关 Skills
448
+
449
+ - `hai-build`:模块初始化顺序
450
+ - `hai-core`:配置管理、HaiResult 模型
451
+ - `hai-iam`:IAM 模块内部使用 reldb 进行用户/角色/权限存储
452
+ - `hai-cache`:缓存穿透保护中配合 reldb 使用
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: hai-scheduler
3
- description: 使用 @h-ai/scheduler 进行统一定时任务管理、任务持久化、手工触发、触发来源审计、全局生命周期回调与执行日志查询;当需求涉及 cron 调度、JS 函数字符串任务、API 任务、分布式锁或任务事件回调时使用。
3
+ description: "使用 @h-ai/scheduler 注册 cron/API/JS/Hook 任务、手工触发并查询执行日志。"
4
4
  ---
5
5
 
6
6
  # hai-scheduler
@@ -19,11 +19,11 @@ API 任务 `timeout` 默认 30000 毫秒,覆盖请求及完整响应体读取
19
19
 
20
20
  | 项目 | 契约 |
21
21
  | --- | --- |
22
- | 能力 | 使用 @h-ai/scheduler 进行统一定时任务管理、任务持久化、手工触发、触发来源审计、全局生命周期回调与执行日志查询;当需求涉及 cron 调度、JS 函数字符串任务、API 任务、分布式锁或任务事件回调时使用。 |
23
- | 适用场景 | 当任务与 `hai-scheduler` 的能力描述匹配,并且需要遵循本 Skill 的流程和边界时 |
24
- | 输入 | 模块配置、类型化业务参数、依赖初始化状态和目标运行环境 |
25
- | 输出 | 符合模块公共 API 的实现或示例;业务结果使用 HaiResult,并同步必要测试与文档 |
26
- | 限制 | 遵守 init → use → close 生命周期与运行环境边界;不绕过类型、授权、输入校验或敏感信息保护 |
22
+ | 能力 | 使用 @h-ai/scheduler 注册 cron/API/JS/Hook 任务、手工触发并查询执行日志 |
23
+ | 适用场景 | 服务端任务调度、持久化和手工触发 |
24
+ | 输入 | SchedulerConfigInput、任务定义、已初始化依赖与 hooks |
25
+ | 输出 | 任务管理、触发和日志查询的 HaiResult |
26
+ | 限制 | 仅服务端;vm 不是安全沙箱,JS 任务只执行可信代码。多节点需要共享锁,关闭释放调度资源。 |
27
27
 
28
28
  > `@h-ai/scheduler` 使用统一任务模型管理 API / JS / Hook 三类执行路径,支持持久化、手工触发来源记录、分布式锁与全局生命周期回调。
29
29