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