@h-ai/reldb 0.1.0-alpha5

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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [2026] [idealworld.group]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,461 @@
1
+ # @h-ai/reldb
2
+
3
+ 关系型数据库访问模块,通过统一的 `reldb` 对象访问 SQLite、PostgreSQL、MySQL。
4
+
5
+ ## 支持的数据库
6
+
7
+ - SQLite
8
+ - PostgreSQL
9
+ - MySQL
10
+
11
+ ## 快速开始
12
+
13
+ ```ts
14
+ import { HaiReldbError, reldb } from '@h-ai/reldb'
15
+
16
+ // 初始化
17
+ await reldb.init({ type: 'sqlite', database: ':memory:' })
18
+
19
+ // DDL
20
+ await reldb.ddl.createTable('users', {
21
+ id: { type: 'INTEGER', primaryKey: true, autoIncrement: true },
22
+ name: { type: 'TEXT', notNull: true },
23
+ email: { type: 'TEXT', unique: true },
24
+ })
25
+
26
+ // SQL
27
+ await reldb.sql.execute('INSERT INTO users (name, email) VALUES (?, ?)', ['张三', 'test@example.com'])
28
+ const users = await reldb.sql.query<{ id: number, name: string }>('SELECT * FROM users')
29
+
30
+ // 分页查询
31
+ const page = await reldb.sql.queryPage<{ id: number, name: string }>({
32
+ sql: 'SELECT id, name FROM users ORDER BY id',
33
+ pagination: { page: 1, pageSize: 20 },
34
+ })
35
+
36
+ // CRUD
37
+ const userCrud = reldb.crud.table({
38
+ table: 'users',
39
+ idColumn: 'id',
40
+ select: ['id', 'name', 'email'],
41
+ createColumns: ['name', 'email'],
42
+ updateColumns: ['name', 'email'],
43
+ dbType: 'sqlite',
44
+ })
45
+ await userCrud.create({ name: '李四', email: 'li@test.com' })
46
+ const user = await userCrud.findById(1)
47
+
48
+ // 关闭
49
+ await reldb.close()
50
+ ```
51
+
52
+ ## 配置
53
+
54
+ 支持连接字符串(`url`)或分字段(`host/port/database/user/password`)。
55
+
56
+ ```ts
57
+ // SQLite
58
+ await reldb.init({ type: 'sqlite', database: './data.db' })
59
+
60
+ // PostgreSQL
61
+ await reldb.init({ type: 'postgresql', url: 'postgres://user:pass@localhost:5432/mydb' })
62
+
63
+ // MySQL
64
+ await reldb.init({
65
+ type: 'mysql',
66
+ host: 'localhost',
67
+ port: 3306,
68
+ database: 'mydb',
69
+ user: 'admin',
70
+ password: 'secret',
71
+ mysql: { charset: 'utf8mb4' },
72
+ })
73
+ ```
74
+
75
+ ## 事务
76
+
77
+ 三种使用方式:
78
+
79
+ ### wrap(自动提交/回滚)
80
+
81
+ ```ts
82
+ const result = await reldb.tx.wrap(async (tx) => {
83
+ await tx.execute('INSERT INTO users (name) VALUES (?)', ['用户1'])
84
+ await tx.execute('INSERT INTO users (name) VALUES (?)', ['用户2'])
85
+ return 'ok'
86
+ })
87
+ // 回调正常返回 → 自动提交;抛异常 → 自动回滚
88
+ ```
89
+
90
+ ### begin + commit(分步提交)
91
+
92
+ ```ts
93
+ const txResult = await reldb.tx.begin()
94
+ if (!txResult.success) { /* 处理错误 */ }
95
+ const tx = txResult.data
96
+
97
+ await tx.execute('INSERT INTO users (name) VALUES (?)', ['用户1'])
98
+ await tx.execute('INSERT INTO users (name) VALUES (?)', ['用户2'])
99
+ await tx.commit()
100
+ ```
101
+
102
+ ### begin + rollback(分步回滚)
103
+
104
+ ```ts
105
+ const txResult = await reldb.tx.begin()
106
+ if (!txResult.success) { /* 处理错误 */ }
107
+ const tx = txResult.data
108
+
109
+ await tx.execute('INSERT INTO users (name) VALUES (?)', ['用户1'])
110
+ // 业务检查失败,手动回滚
111
+ await tx.rollback()
112
+ ```
113
+
114
+ ### 事务内使用 batch / queryPage
115
+
116
+ ```ts
117
+ await reldb.tx.wrap(async (tx) => {
118
+ await tx.batch([
119
+ { sql: 'INSERT INTO users (name) VALUES (?)', params: ['用户1'] },
120
+ { sql: 'INSERT INTO users (name) VALUES (?)', params: ['用户2'] },
121
+ ])
122
+
123
+ const page = await tx.queryPage<{ id: number, name: string }>({
124
+ sql: 'SELECT id, name FROM users ORDER BY id',
125
+ pagination: { page: 1, pageSize: 10 },
126
+ })
127
+ })
128
+ ```
129
+
130
+ ## Crud
131
+
132
+ 通过 `reldb.crud.table()` 创建单表 CRUD 仓库,免写 SQL:
133
+
134
+ ```ts
135
+ const userCrud = reldb.crud.table<{ id: number, name: string, email: string }>({
136
+ table: 'users',
137
+ idColumn: 'id', // 主键列,默认 'id'
138
+ select: ['id', 'name', 'email'], // 查询列,默认 '*'
139
+ createColumns: ['name', 'email'], // 允许插入的列
140
+ updateColumns: ['name', 'email'], // 允许更新的列
141
+ dbType: 'sqlite', // 数据库类型
142
+ })
143
+ ```
144
+
145
+ ### create / createMany
146
+
147
+ ```ts
148
+ // 单条插入
149
+ const result = await userCrud.create({ name: '张三', email: 'test@example.com' })
150
+ // result.data → { changes: 1, lastInsertRowid: 1 }
151
+
152
+ // 批量插入
153
+ await userCrud.createMany([
154
+ { name: '用户A', email: 'a@test.com' },
155
+ { name: '用户B', email: 'b@test.com' },
156
+ ])
157
+ ```
158
+
159
+ ### createOrUpdate
160
+
161
+ 主键存在时更新,否则创建(upsert):
162
+
163
+ ```ts
164
+ const userCrud = reldb.crud.table<{ id: number, name: string, email: string }>({
165
+ table: 'users',
166
+ idColumn: 'id',
167
+ createColumns: ['id', 'name', 'email'],
168
+ updateColumns: ['name', 'email'],
169
+ dbType: 'sqlite',
170
+ })
171
+
172
+ await userCrud.createOrUpdate({ id: 1, name: '张三', email: 'test@example.com' })
173
+ // 不存在 → 插入;已存在 → 更新 name、email
174
+ ```
175
+
176
+ `BaseReldbCrudRepository` 自动获取 `dbType`,无需手动传入。
177
+
178
+ ### findById / getById / findAll / findPage
179
+
180
+ ```ts
181
+ // 主键查找(不存在时返回 null)
182
+ const user = await userCrud.findById(1)
183
+ // user.data → { id: 1, name: '张三', email: 'test@example.com' } | null
184
+
185
+ // 主键获取(不存在时返回 RECORD_NOT_FOUND 错误)
186
+ const user2 = await userCrud.getById(1)
187
+ // user2.data → { id: 1, name: '张三', email: 'test@example.com' }
188
+
189
+ // 条件查询(where + params 占位符)
190
+ const actives = await userCrud.findAll({
191
+ where: 'name LIKE ?',
192
+ params: ['%张%'],
193
+ orderBy: 'id DESC',
194
+ limit: 10,
195
+ offset: 0,
196
+ })
197
+
198
+ // 分页查询
199
+ const page = await userCrud.findPage({
200
+ where: 'name LIKE ?',
201
+ params: ['%张%'],
202
+ orderBy: 'id DESC',
203
+ pagination: { page: 1, pageSize: 20 },
204
+ })
205
+ // page.data → { items: [...], total: 100, page: 1, pageSize: 20 }
206
+ ```
207
+
208
+ ### updateById / deleteById
209
+
210
+ ```ts
211
+ await userCrud.updateById(1, { name: '李四' })
212
+ await userCrud.deleteById(1)
213
+ ```
214
+
215
+ ### count / exists / existsById
216
+
217
+ ```ts
218
+ const total = await userCrud.count({ where: 'name LIKE ?', params: ['%张%'] })
219
+ // total.data → 5
220
+
221
+ const has = await userCrud.exists({ where: 'email = ?', params: ['test@example.com'] })
222
+ // has.data → true
223
+
224
+ const found = await userCrud.existsById(1)
225
+ // found.data → true
226
+ ```
227
+
228
+ ### 事务中使用 Crud
229
+
230
+ 所有方法均支持传入 `tx` 参数,自动路由到事务上下文:
231
+
232
+ ```ts
233
+ await reldb.tx.wrap(async (tx) => {
234
+ await userCrud.create({ name: '用户A', email: 'a@test.com' }, tx)
235
+ await userCrud.updateById(1, { name: '新名字' }, tx)
236
+ const user = await userCrud.findById(1, tx)
237
+ })
238
+ ```
239
+
240
+ ## BaseReldbCrudRepository
241
+
242
+ 业务仓库继承 `BaseReldbCrudRepository`,通过 `fields` 定义字段映射,自动建表、类型转换:
243
+
244
+ ```ts
245
+ import type { DmlWithTxOperations, ReldbCrudFieldDefinition } from '@h-ai/reldb'
246
+ import { BaseReldbCrudRepository, reldb } from '@h-ai/reldb'
247
+
248
+ interface UserRow {
249
+ id: number
250
+ name: string
251
+ email: string
252
+ createdAt: Date
253
+ updatedAt: Date
254
+ }
255
+
256
+ const USER_FIELDS: ReldbCrudFieldDefinition[] = [
257
+ { fieldName: 'id', columnName: 'id', def: { type: 'INTEGER', primaryKey: true, autoIncrement: true }, select: true, create: false, update: false },
258
+ { fieldName: 'name', columnName: 'name', def: { type: 'TEXT', notNull: true }, select: true, create: true, update: true },
259
+ { fieldName: 'email', columnName: 'email', def: { type: 'TEXT', notNull: true }, select: true, create: true, update: true },
260
+ { fieldName: 'createdAt', columnName: 'created_at', def: { type: 'TIMESTAMP', notNull: true }, select: true, create: true, update: false },
261
+ { fieldName: 'updatedAt', columnName: 'updated_at', def: { type: 'TIMESTAMP', notNull: true }, select: true, create: true, update: false },
262
+ ]
263
+
264
+ class UserRepository extends BaseReldbCrudRepository<UserRow> {
265
+ constructor() {
266
+ super(reldb, { table: 'users', idColumn: 'id', fields: USER_FIELDS })
267
+ }
268
+
269
+ /** 自定义查询方法 */
270
+ async findByEmail(email: string) {
271
+ return this.findAll({ where: 'email = ?', params: [email], limit: 1 })
272
+ }
273
+
274
+ /** 自定义方法中使用 this.sql(tx) 自动路由到事务 */
275
+ async insertRaw(data: { name: string, email: string }, tx?: DmlWithTxOperations) {
276
+ const now = Date.now()
277
+ return this.sql(tx).execute(
278
+ 'INSERT INTO users (name, email, created_at, updated_at) VALUES (?, ?, ?, ?)',
279
+ [data.name, data.email, now, now],
280
+ )
281
+ }
282
+ }
283
+
284
+ // 使用
285
+ const repo = new UserRepository()
286
+ await repo.create({ name: '张三', email: 'test@example.com' })
287
+ const user = await repo.findById(1)
288
+
289
+ // 创建或更新(upsert)
290
+ await repo.createOrUpdate({ id: 1, name: '李四', email: 'test@example.com' })
291
+ // id=1 已存在 → 更新 name;不存在 → 插入新记录
292
+
293
+ // 跨仓库事务
294
+ const txResult = await reldb.tx.begin()
295
+ if (txResult.success) {
296
+ const tx = txResult.data
297
+ await repo.create({ name: '用户A', email: 'a@test.com' }, tx)
298
+ await repo.create({ name: '用户B', email: 'b@test.com' }, tx)
299
+ await tx.commit()
300
+ }
301
+ ```
302
+
303
+ ## JSON 路径操作
304
+
305
+ 通过 `reldb.json` 构建跨数据库统一的 JSON 路径操作 SQL 表达式。
306
+
307
+ 路径格式遵循 SQL/JSON Path 标准(`$.key` / `$.key.subkey` / `$[0]`),各数据库后端自动映射到对应函数或操作符。
308
+
309
+ | 操作 | SQLite | PostgreSQL | MySQL |
310
+ | --------- | -------------- | -------------- | ------------------ |
311
+ | `extract` | `json_extract` | `#>` (text[]) | `JSON_EXTRACT` |
312
+ | `set` | `json_set` | `jsonb_set` | `JSON_SET` |
313
+ | `insert` | `json_insert` | `jsonb_insert` | `JSON_INSERT` |
314
+ | `remove` | `json_remove` | `#-` (text[]) | `JSON_REMOVE` |
315
+ | `merge` | `json_patch` | `\|\| ::jsonb` | `JSON_MERGE_PATCH` |
316
+
317
+ 所有方法返回 `{ sql, params }` 片段,可直接嵌入 `reldb.sql.query` / `reldb.sql.execute`。
318
+
319
+ ### extract — 提取 JSON 字段值
320
+
321
+ ```ts
322
+ // 用于 WHERE 条件
323
+ const { sql, params } = reldb.json.extract('settings', '$.theme')
324
+ const rows = await reldb.sql.query(
325
+ `SELECT * FROM users WHERE ${sql} = ?`,
326
+ [...params, '"dark"'],
327
+ )
328
+
329
+ // 用于 SELECT 列
330
+ const { sql, params } = reldb.json.extract('profile', '$.name')
331
+ const result = await reldb.sql.query(
332
+ `SELECT id, ${sql} as display_name FROM users`,
333
+ params,
334
+ )
335
+ ```
336
+
337
+ ### set — 设置 JSON 字段路径(创建或替换)
338
+
339
+ ```ts
340
+ const { sql, params } = reldb.json.set('settings', '$.theme', 'dark')
341
+ await reldb.sql.execute(
342
+ `UPDATE users SET settings = ${sql} WHERE id = ?`,
343
+ [...params, userId],
344
+ )
345
+ ```
346
+
347
+ ### insert — 插入 JSON 字段路径(仅当路径不存在时)
348
+
349
+ ```ts
350
+ const { sql, params } = reldb.json.insert('data', '$.firstSeen', new Date().toISOString())
351
+ await reldb.sql.execute(
352
+ `UPDATE events SET data = ${sql} WHERE id = ?`,
353
+ [...params, eventId],
354
+ )
355
+ ```
356
+
357
+ ### remove — 删除 JSON 字段路径
358
+
359
+ ```ts
360
+ const { sql, params } = reldb.json.remove('settings', '$.deprecated')
361
+ await reldb.sql.execute(
362
+ `UPDATE users SET settings = ${sql} WHERE id = ?`,
363
+ [...params, userId],
364
+ )
365
+ ```
366
+
367
+ ### merge — 合并 JSON 对象(RFC 7396 Merge Patch)
368
+
369
+ ```ts
370
+ // 覆盖已有键、保留未提及键、将 null 键删除
371
+ const { sql, params } = reldb.json.merge('profile', {
372
+ bio: '新简介',
373
+ avatar: null, // 传入 null 表示删除该键
374
+ })
375
+ await reldb.sql.execute(
376
+ `UPDATE users SET profile = ${sql} WHERE id = ?`,
377
+ [...params, userId],
378
+ )
379
+ ```
380
+
381
+ ### 完整示例
382
+
383
+ ```ts
384
+ // 建表(含 JSON 列)
385
+ await reldb.ddl.createTable('products', {
386
+ id: { type: 'INTEGER', primaryKey: true, autoIncrement: true },
387
+ meta: { type: 'JSON' },
388
+ })
389
+
390
+ // 插入初始 JSON
391
+ await reldb.sql.execute(
392
+ `INSERT INTO products (meta) VALUES (?)`,
393
+ [JSON.stringify({ status: 'draft', tags: ['new'], version: 1 })],
394
+ )
395
+
396
+ // 设置字段
397
+ const { sql: setSql, params: setParams } = reldb.json.set('meta', '$.status', 'published')
398
+ await reldb.sql.execute(`UPDATE products SET meta = ${setSql} WHERE id = ?`, [...setParams, 1])
399
+
400
+ // 提取字段(用于过滤)
401
+ const { sql: exSql, params: exParams } = reldb.json.extract('meta', '$.status')
402
+ const published = await reldb.sql.query(
403
+ `SELECT * FROM products WHERE ${exSql} = ?`,
404
+ [...exParams, '"published"'],
405
+ )
406
+
407
+ // 合并更新
408
+ const { sql: mSql, params: mParams } = reldb.json.merge('meta', { version: 2, reviewer: 'admin' })
409
+ await reldb.sql.execute(`UPDATE products SET meta = ${mSql} WHERE id = ?`, [...mParams, 1])
410
+
411
+ // 删除字段
412
+ const { sql: rmSql, params: rmParams } = reldb.json.remove('meta', '$.reviewer')
413
+ await reldb.sql.execute(`UPDATE products SET meta = ${rmSql} WHERE id = ?`, [...rmParams, 1])
414
+ ```
415
+
416
+ ## 错误处理
417
+
418
+ 所有操作返回 `HaiResult<T>`,通过 `result.success` 判断成功或失败。
419
+
420
+ ```ts
421
+ import { HaiReldbError, reldb } from '@h-ai/reldb'
422
+
423
+ const result = await reldb.sql.query('SELECT * FROM users')
424
+ if (!result.success) {
425
+ switch (result.error.code) {
426
+ case HaiReldbError.NOT_INITIALIZED.code:
427
+ // 请先调用 reldb.init()
428
+ break
429
+ case HaiReldbError.QUERY_FAILED.code:
430
+ // SQL 执行错误
431
+ break
432
+ case HaiReldbError.CONSTRAINT_VIOLATION.code:
433
+ // 约束违反(如唯一约束、外键等)
434
+ break
435
+ }
436
+ }
437
+ ```
438
+
439
+ 常用错误码:
440
+
441
+ | 错误码 | code | 说明 |
442
+ | ------------------------------------ | --------------- | ------------ |
443
+ | `HaiReldbError.NOT_INITIALIZED` | `hai:reldb:011` | 未初始化 |
444
+ | `HaiReldbError.CONNECTION_FAILED` | `hai:reldb:001` | 连接失败 |
445
+ | `HaiReldbError.QUERY_FAILED` | `hai:reldb:002` | 查询失败 |
446
+ | `HaiReldbError.CONSTRAINT_VIOLATION` | `hai:reldb:003` | 约束违反 |
447
+ | `HaiReldbError.TRANSACTION_FAILED` | `hai:reldb:004` | 事务失败 |
448
+ | `HaiReldbError.DDL_FAILED` | `hai:reldb:012` | DDL 操作失败 |
449
+ | `HaiReldbError.CONFIG_ERROR` | `hai:reldb:014` | 配置错误 |
450
+
451
+ ## 测试
452
+
453
+ ```bash
454
+ pnpm --filter @h-ai/reldb test
455
+ ```
456
+
457
+ > MySQL/PostgreSQL 测试需要 Docker。
458
+
459
+ ## License
460
+
461
+ Apache-2.0