@molecule/api-database 1.0.2 → 1.1.1
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 +111 -24
- package/README.md +337 -303
- package/dist/index.d.ts +12 -16
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -16
- package/dist/index.js.map +1 -1
- package/dist/transaction-context.d.ts +46 -0
- package/dist/transaction-context.d.ts.map +1 -0
- package/dist/transaction-context.js +82 -0
- package/dist/transaction-context.js.map +1 -0
- package/package.json +1 -1
package/LICENSE
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
|
|
1
2
|
Apache License
|
|
2
3
|
Version 2.0, January 2004
|
|
3
4
|
http://www.apache.org/licenses/
|
|
@@ -34,21 +35,33 @@
|
|
|
34
35
|
|
|
35
36
|
"Work" shall mean the work of authorship, whether in Source or
|
|
36
37
|
Object form, made available under the License, as indicated by a
|
|
37
|
-
copyright notice that is included in or attached to the work
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
38
40
|
|
|
39
41
|
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
42
|
form, that is based on (or derived from) the Work and for which the
|
|
41
43
|
editorial revisions, annotations, elaborations, or other modifications
|
|
42
|
-
represent, as a whole, an original work of authorship.
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
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."
|
|
49
62
|
|
|
50
63
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
51
|
-
on behalf of whom a Contribution has been received by
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
52
65
|
subsequently incorporated within the Work.
|
|
53
66
|
|
|
54
67
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
@@ -61,8 +74,18 @@
|
|
|
61
74
|
3. Grant of Patent License. Subject to the terms and conditions of
|
|
62
75
|
this License, each Contributor hereby grants to You a perpetual,
|
|
63
76
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
64
|
-
|
|
65
|
-
and otherwise transfer the Work
|
|
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.
|
|
66
89
|
|
|
67
90
|
4. Redistribution. You may reproduce and distribute copies of the
|
|
68
91
|
Work or Derivative Works thereof in any medium, with or without
|
|
@@ -84,23 +107,87 @@
|
|
|
84
107
|
(d) If the Work includes a "NOTICE" text file as part of its
|
|
85
108
|
distribution, then any Derivative Works that You distribute must
|
|
86
109
|
include a readable copy of the attribution notices contained
|
|
87
|
-
within such NOTICE file
|
|
88
|
-
|
|
89
|
-
|
|
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.
|
|
90
138
|
|
|
91
139
|
6. Trademarks. This License does not grant permission to use the trade
|
|
92
|
-
names, trademarks, service marks, or product names of the Licensor
|
|
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.
|
|
93
143
|
|
|
94
144
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
95
|
-
agreed to in writing, Licensor provides the Work
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
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 [yyyy] [name of copyright owner]
|
|
104
191
|
|
|
105
192
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
106
193
|
you may not use this file except in compliance with the License.
|
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@ AUTO-GENERATED — DO NOT EDIT THIS FILE.
|
|
|
3
3
|
Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
|
|
4
4
|
Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
|
|
5
5
|
To change this document, edit the module-level JSDoc in src/index.ts.
|
|
6
|
-
Generated: 2026-
|
|
6
|
+
Generated: 2026-10-16T00:26:28.689Z
|
|
7
7
|
-->
|
|
8
8
|
|
|
9
9
|
# @molecule/api-database
|
|
@@ -61,73 +61,183 @@ npm install @molecule/api-database @molecule/api-bond @molecule/api-i18n
|
|
|
61
61
|
|
|
62
62
|
### Interfaces
|
|
63
63
|
|
|
64
|
-
#### `
|
|
64
|
+
#### `WhereCondition`
|
|
65
65
|
|
|
66
|
-
|
|
66
|
+
Filter condition for queries.
|
|
67
67
|
|
|
68
68
|
```typescript
|
|
69
|
-
interface
|
|
69
|
+
interface WhereCondition {
|
|
70
|
+
field: string
|
|
71
|
+
operator:
|
|
72
|
+
| '='
|
|
73
|
+
| '!='
|
|
74
|
+
| '>'
|
|
75
|
+
| '<'
|
|
76
|
+
| '>='
|
|
77
|
+
| '<='
|
|
78
|
+
| 'in'
|
|
79
|
+
| 'not_in'
|
|
80
|
+
/**
|
|
81
|
+
* Case-insensitive SQL pattern match. `value` is used AS-IS as the raw
|
|
82
|
+
* LIKE pattern: `%` matches any run of characters, `_` matches any
|
|
83
|
+
* single character, and the CALLER is responsible for escaping any
|
|
84
|
+
* literal `%` / `_` / `\` they don't want treated as wildcards. All
|
|
85
|
+
* three first-party bonds (postgresql, mysql, sqlite) implement `like`
|
|
86
|
+
* case-INSENSITIVELY — postgres via `ILIKE`, mysql/sqlite via
|
|
87
|
+
* `LOWER()` on both sides — specifically so this operator has
|
|
88
|
+
* IDENTICAL results across every bond regardless of column collation
|
|
89
|
+
* or `PRAGMA case_sensitive_like`. Prior to this contract the postgres
|
|
90
|
+
* bond escaped the value (making `like` an exact-match operator there
|
|
91
|
+
* only) while sqlite/mysql passed it through raw — the same `{
|
|
92
|
+
* operator: 'like', value: `%${search}%` }` filter silently matched
|
|
93
|
+
* nothing on postgres and worked everywhere else. For human-typed
|
|
94
|
+
* search input where the value should be a literal substring (not a
|
|
95
|
+
* pattern the caller controls), use `ilike` instead — it escapes
|
|
96
|
+
* wildcards and wraps `%…%` for you, so it is injection-safe for
|
|
97
|
+
* arbitrary user text.
|
|
98
|
+
*/
|
|
99
|
+
| 'like'
|
|
100
|
+
/**
|
|
101
|
+
* Case-insensitive substring match. The value is treated as a
|
|
102
|
+
* literal substring (LIKE wildcards in the value are escaped) and
|
|
103
|
+
* the bond wraps it with `%…%` to perform a contains-style match.
|
|
104
|
+
* Use this for human-typed search input where case shouldn't matter.
|
|
105
|
+
*/
|
|
106
|
+
| 'ilike'
|
|
107
|
+
| 'is_null'
|
|
108
|
+
| 'is_not_null'
|
|
109
|
+
value?: unknown
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
#### `OrderBy`
|
|
114
|
+
|
|
115
|
+
Column sort order (field name and ascending/descending direction).
|
|
116
|
+
|
|
117
|
+
```typescript
|
|
118
|
+
interface OrderBy {
|
|
119
|
+
field: string
|
|
120
|
+
direction: 'asc' | 'desc'
|
|
121
|
+
}
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
#### `FindManyOptions`
|
|
125
|
+
|
|
126
|
+
Options for findMany queries.
|
|
127
|
+
|
|
128
|
+
```typescript
|
|
129
|
+
interface FindManyOptions {
|
|
130
|
+
where?: WhereCondition[]
|
|
131
|
+
orderBy?: OrderBy[]
|
|
132
|
+
limit?: number
|
|
133
|
+
offset?: number
|
|
134
|
+
select?: string[]
|
|
135
|
+
}
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
#### `MutationResult`
|
|
139
|
+
|
|
140
|
+
Result of a mutation operation.
|
|
141
|
+
|
|
142
|
+
```typescript
|
|
143
|
+
interface MutationResult<T = Record<string, unknown>> {
|
|
144
|
+
/** The affected/returned row, if any. */
|
|
145
|
+
data: T | null
|
|
146
|
+
/** Number of rows affected. */
|
|
147
|
+
affected: number
|
|
148
|
+
}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
#### `DataStore`
|
|
152
|
+
|
|
153
|
+
Abstract data store interface.
|
|
154
|
+
|
|
155
|
+
Provides database-agnostic CRUD methods. Each database bond
|
|
156
|
+
implements these using its native query language.
|
|
157
|
+
|
|
158
|
+
```typescript
|
|
159
|
+
interface DataStore {
|
|
70
160
|
/**
|
|
71
|
-
*
|
|
161
|
+
* Find a single record by its primary key.
|
|
72
162
|
*/
|
|
73
|
-
|
|
163
|
+
findById<T = Record<string, unknown>>(table: string, id: string | number): Promise<T | null>
|
|
74
164
|
|
|
75
165
|
/**
|
|
76
|
-
*
|
|
166
|
+
* Find a single record matching conditions.
|
|
77
167
|
*/
|
|
78
|
-
|
|
168
|
+
findOne<T = Record<string, unknown>>(table: string, where: WhereCondition[]): Promise<T | null>
|
|
79
169
|
|
|
80
170
|
/**
|
|
81
|
-
*
|
|
171
|
+
* Find many records with filtering, sorting, and pagination.
|
|
82
172
|
*/
|
|
83
|
-
|
|
173
|
+
findMany<T = Record<string, unknown>>(table: string, options?: FindManyOptions): Promise<T[]>
|
|
84
174
|
|
|
85
175
|
/**
|
|
86
|
-
*
|
|
176
|
+
* Count records matching conditions.
|
|
87
177
|
*/
|
|
88
|
-
|
|
178
|
+
count(table: string, where?: WhereCondition[]): Promise<number>
|
|
89
179
|
|
|
90
180
|
/**
|
|
91
|
-
*
|
|
181
|
+
* Insert a new record. Returns the inserted row.
|
|
92
182
|
*/
|
|
93
|
-
|
|
183
|
+
create<T = Record<string, unknown>>(
|
|
184
|
+
table: string,
|
|
185
|
+
data: Record<string, unknown>,
|
|
186
|
+
): Promise<MutationResult<T>>
|
|
94
187
|
|
|
95
188
|
/**
|
|
96
|
-
*
|
|
189
|
+
* Update a record by primary key. Returns the updated row.
|
|
97
190
|
*/
|
|
98
|
-
|
|
191
|
+
updateById<T = Record<string, unknown>>(
|
|
192
|
+
table: string,
|
|
193
|
+
id: string | number,
|
|
194
|
+
data: Record<string, unknown>,
|
|
195
|
+
): Promise<MutationResult<T>>
|
|
99
196
|
|
|
100
197
|
/**
|
|
101
|
-
*
|
|
198
|
+
* Update records matching conditions.
|
|
102
199
|
*/
|
|
103
|
-
|
|
200
|
+
updateMany(
|
|
201
|
+
table: string,
|
|
202
|
+
where: WhereCondition[],
|
|
203
|
+
data: Record<string, unknown>,
|
|
204
|
+
): Promise<MutationResult>
|
|
104
205
|
|
|
105
206
|
/**
|
|
106
|
-
*
|
|
207
|
+
* Delete a record by primary key.
|
|
107
208
|
*/
|
|
108
|
-
|
|
209
|
+
deleteById(table: string, id: string | number): Promise<MutationResult>
|
|
109
210
|
|
|
110
211
|
/**
|
|
111
|
-
*
|
|
212
|
+
* Delete records matching conditions.
|
|
112
213
|
*/
|
|
113
|
-
|
|
214
|
+
deleteMany(table: string, where: WhereCondition[]): Promise<MutationResult>
|
|
215
|
+
}
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
#### `QueryResult`
|
|
219
|
+
|
|
220
|
+
Query result with rows and metadata.
|
|
114
221
|
|
|
222
|
+
```typescript
|
|
223
|
+
interface QueryResult<T = Record<string, unknown>> {
|
|
115
224
|
/**
|
|
116
|
-
*
|
|
225
|
+
* Array of rows returned by the query.
|
|
117
226
|
*/
|
|
118
|
-
|
|
227
|
+
rows: T[]
|
|
119
228
|
|
|
120
229
|
/**
|
|
121
|
-
*
|
|
230
|
+
* Number of rows affected (for INSERT, UPDATE, DELETE).
|
|
122
231
|
*/
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
232
|
+
rowCount: number | null
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Column metadata (optional, provider-dependent).
|
|
236
|
+
*/
|
|
237
|
+
fields?: Array<{
|
|
238
|
+
name: string
|
|
239
|
+
dataTypeID?: number
|
|
240
|
+
}>
|
|
131
241
|
}
|
|
132
242
|
```
|
|
133
243
|
|
|
@@ -152,6 +262,24 @@ interface DatabaseConnection {
|
|
|
152
262
|
}
|
|
153
263
|
```
|
|
154
264
|
|
|
265
|
+
#### `DatabaseTransaction`
|
|
266
|
+
|
|
267
|
+
Database transaction with commit and rollback (extends DatabaseConnection).
|
|
268
|
+
|
|
269
|
+
```typescript
|
|
270
|
+
interface DatabaseTransaction extends DatabaseConnection {
|
|
271
|
+
/**
|
|
272
|
+
* Commits the transaction.
|
|
273
|
+
*/
|
|
274
|
+
commit(): Promise<void>
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Rolls back the transaction.
|
|
278
|
+
*/
|
|
279
|
+
rollback(): Promise<void>
|
|
280
|
+
}
|
|
281
|
+
```
|
|
282
|
+
|
|
155
283
|
#### `DatabasePool`
|
|
156
284
|
|
|
157
285
|
Database pool interface.
|
|
@@ -212,205 +340,121 @@ interface DatabaseProvider {
|
|
|
212
340
|
}
|
|
213
341
|
```
|
|
214
342
|
|
|
215
|
-
#### `
|
|
343
|
+
#### `DatabaseConfig`
|
|
216
344
|
|
|
217
|
-
Database
|
|
345
|
+
Database connection options (host, port, credentials, pool size, timeouts, SSL).
|
|
218
346
|
|
|
219
347
|
```typescript
|
|
220
|
-
interface
|
|
348
|
+
interface DatabaseConfig {
|
|
221
349
|
/**
|
|
222
|
-
*
|
|
350
|
+
* Database host.
|
|
223
351
|
*/
|
|
224
|
-
|
|
352
|
+
host?: string
|
|
225
353
|
|
|
226
354
|
/**
|
|
227
|
-
*
|
|
355
|
+
* Database port.
|
|
228
356
|
*/
|
|
229
|
-
|
|
230
|
-
}
|
|
231
|
-
```
|
|
232
|
-
|
|
233
|
-
#### `DataStore`
|
|
234
|
-
|
|
235
|
-
Abstract data store interface.
|
|
236
|
-
|
|
237
|
-
Provides database-agnostic CRUD methods. Each database bond
|
|
238
|
-
implements these using its native query language.
|
|
357
|
+
port?: number
|
|
239
358
|
|
|
240
|
-
```typescript
|
|
241
|
-
interface DataStore {
|
|
242
359
|
/**
|
|
243
|
-
*
|
|
360
|
+
* Database name.
|
|
244
361
|
*/
|
|
245
|
-
|
|
362
|
+
database?: string
|
|
246
363
|
|
|
247
364
|
/**
|
|
248
|
-
*
|
|
365
|
+
* Database user.
|
|
249
366
|
*/
|
|
250
|
-
|
|
367
|
+
user?: string
|
|
251
368
|
|
|
252
369
|
/**
|
|
253
|
-
*
|
|
370
|
+
* Database password.
|
|
254
371
|
*/
|
|
255
|
-
|
|
372
|
+
password?: string
|
|
256
373
|
|
|
257
374
|
/**
|
|
258
|
-
*
|
|
375
|
+
* Connection string (alternative to individual fields).
|
|
259
376
|
*/
|
|
260
|
-
|
|
377
|
+
connectionString?: string
|
|
261
378
|
|
|
262
379
|
/**
|
|
263
|
-
*
|
|
380
|
+
* Maximum number of connections in the pool.
|
|
264
381
|
*/
|
|
265
|
-
|
|
266
|
-
table: string,
|
|
267
|
-
data: Record<string, unknown>,
|
|
268
|
-
): Promise<MutationResult<T>>
|
|
382
|
+
max?: number
|
|
269
383
|
|
|
270
384
|
/**
|
|
271
|
-
*
|
|
385
|
+
* Minimum number of connections in the pool.
|
|
272
386
|
*/
|
|
273
|
-
|
|
274
|
-
table: string,
|
|
275
|
-
id: string | number,
|
|
276
|
-
data: Record<string, unknown>,
|
|
277
|
-
): Promise<MutationResult<T>>
|
|
387
|
+
min?: number
|
|
278
388
|
|
|
279
389
|
/**
|
|
280
|
-
*
|
|
390
|
+
* Connection timeout in milliseconds.
|
|
281
391
|
*/
|
|
282
|
-
|
|
283
|
-
table: string,
|
|
284
|
-
where: WhereCondition[],
|
|
285
|
-
data: Record<string, unknown>,
|
|
286
|
-
): Promise<MutationResult>
|
|
392
|
+
connectionTimeoutMillis?: number
|
|
287
393
|
|
|
288
394
|
/**
|
|
289
|
-
*
|
|
395
|
+
* Idle timeout in milliseconds.
|
|
290
396
|
*/
|
|
291
|
-
|
|
397
|
+
idleTimeoutMillis?: number
|
|
292
398
|
|
|
293
399
|
/**
|
|
294
|
-
*
|
|
400
|
+
* Enable SSL.
|
|
295
401
|
*/
|
|
296
|
-
|
|
402
|
+
ssl?:
|
|
403
|
+
| boolean
|
|
404
|
+
| {
|
|
405
|
+
rejectUnauthorized?: boolean
|
|
406
|
+
ca?: string
|
|
407
|
+
key?: string
|
|
408
|
+
cert?: string
|
|
409
|
+
}
|
|
297
410
|
}
|
|
298
411
|
```
|
|
299
412
|
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
Options for findMany queries.
|
|
303
|
-
|
|
304
|
-
```typescript
|
|
305
|
-
interface FindManyOptions {
|
|
306
|
-
where?: WhereCondition[]
|
|
307
|
-
orderBy?: OrderBy[]
|
|
308
|
-
limit?: number
|
|
309
|
-
offset?: number
|
|
310
|
-
select?: string[]
|
|
311
|
-
}
|
|
312
|
-
```
|
|
413
|
+
### Functions
|
|
313
414
|
|
|
314
|
-
#### `
|
|
415
|
+
#### `setPool(pool)`
|
|
315
416
|
|
|
316
|
-
|
|
417
|
+
Registers a database connection pool as the active singleton. Called by
|
|
418
|
+
bond packages during application startup.
|
|
317
419
|
|
|
318
420
|
```typescript
|
|
319
|
-
|
|
320
|
-
/** The affected/returned row, if any. */
|
|
321
|
-
data: T | null
|
|
322
|
-
/** Number of rows affected. */
|
|
323
|
-
affected: number
|
|
324
|
-
}
|
|
421
|
+
function setPool(pool: DatabasePool): void
|
|
325
422
|
```
|
|
326
423
|
|
|
327
|
-
|
|
424
|
+
- `pool` — The database pool implementation to bond.
|
|
328
425
|
|
|
329
|
-
|
|
426
|
+
#### `getPool()`
|
|
427
|
+
|
|
428
|
+
Retrieves the bonded database pool, throwing if none is configured.
|
|
330
429
|
|
|
331
430
|
```typescript
|
|
332
|
-
|
|
333
|
-
field: string
|
|
334
|
-
direction: 'asc' | 'desc'
|
|
335
|
-
}
|
|
431
|
+
function getPool(): DatabasePool
|
|
336
432
|
```
|
|
337
433
|
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
Query result with rows and metadata.
|
|
434
|
+
**Returns:** The bonded database pool.
|
|
341
435
|
|
|
342
|
-
|
|
343
|
-
interface QueryResult<T = Record<string, unknown>> {
|
|
344
|
-
/**
|
|
345
|
-
* Array of rows returned by the query.
|
|
346
|
-
*/
|
|
347
|
-
rows: T[]
|
|
436
|
+
#### `hasPool()`
|
|
348
437
|
|
|
349
|
-
|
|
350
|
-
* Number of rows affected (for INSERT, UPDATE, DELETE).
|
|
351
|
-
*/
|
|
352
|
-
rowCount: number | null
|
|
438
|
+
Checks whether a database pool is currently bonded.
|
|
353
439
|
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
*/
|
|
357
|
-
fields?: Array<{
|
|
358
|
-
name: string
|
|
359
|
-
dataTypeID?: number
|
|
360
|
-
}>
|
|
361
|
-
}
|
|
440
|
+
```typescript
|
|
441
|
+
function hasPool(): boolean
|
|
362
442
|
```
|
|
363
443
|
|
|
364
|
-
|
|
444
|
+
**Returns:** `true` if a database pool is bonded.
|
|
365
445
|
|
|
366
|
-
|
|
446
|
+
#### `query(text, values)`
|
|
447
|
+
|
|
448
|
+
Executes a parameterized SQL query using the bonded pool.
|
|
367
449
|
|
|
368
450
|
```typescript
|
|
369
|
-
|
|
370
|
-
field: string
|
|
371
|
-
operator:
|
|
372
|
-
| '='
|
|
373
|
-
| '!='
|
|
374
|
-
| '>'
|
|
375
|
-
| '<'
|
|
376
|
-
| '>='
|
|
377
|
-
| '<='
|
|
378
|
-
| 'in'
|
|
379
|
-
| 'not_in'
|
|
380
|
-
/**
|
|
381
|
-
* Case-insensitive SQL pattern match. `value` is used AS-IS as the raw
|
|
382
|
-
* LIKE pattern: `%` matches any run of characters, `_` matches any
|
|
383
|
-
* single character, and the CALLER is responsible for escaping any
|
|
384
|
-
* literal `%` / `_` / `\` they don't want treated as wildcards. All
|
|
385
|
-
* three first-party bonds (postgresql, mysql, sqlite) implement `like`
|
|
386
|
-
* case-INSENSITIVELY — postgres via `ILIKE`, mysql/sqlite via
|
|
387
|
-
* `LOWER()` on both sides — specifically so this operator has
|
|
388
|
-
* IDENTICAL results across every bond regardless of column collation
|
|
389
|
-
* or `PRAGMA case_sensitive_like`. Prior to this contract the postgres
|
|
390
|
-
* bond escaped the value (making `like` an exact-match operator there
|
|
391
|
-
* only) while sqlite/mysql passed it through raw — the same `{
|
|
392
|
-
* operator: 'like', value: `%${search}%` }` filter silently matched
|
|
393
|
-
* nothing on postgres and worked everywhere else. For human-typed
|
|
394
|
-
* search input where the value should be a literal substring (not a
|
|
395
|
-
* pattern the caller controls), use `ilike` instead — it escapes
|
|
396
|
-
* wildcards and wraps `%…%` for you, so it is injection-safe for
|
|
397
|
-
* arbitrary user text.
|
|
398
|
-
*/
|
|
399
|
-
| 'like'
|
|
400
|
-
/**
|
|
401
|
-
* Case-insensitive substring match. The value is treated as a
|
|
402
|
-
* literal substring (LIKE wildcards in the value are escaped) and
|
|
403
|
-
* the bond wraps it with `%…%` to perform a contains-style match.
|
|
404
|
-
* Use this for human-typed search input where case shouldn't matter.
|
|
405
|
-
*/
|
|
406
|
-
| 'ilike'
|
|
407
|
-
| 'is_null'
|
|
408
|
-
| 'is_not_null'
|
|
409
|
-
value?: unknown
|
|
410
|
-
}
|
|
451
|
+
function query(text: string, values?: unknown[]): Promise<QueryResult<T>>
|
|
411
452
|
```
|
|
412
453
|
|
|
413
|
-
|
|
454
|
+
- `text` — SQL query text with placeholders (`$1`, `$2`, etc.).
|
|
455
|
+
- `values` — Parameter values corresponding to the placeholders.
|
|
456
|
+
|
|
457
|
+
**Returns:** The query result containing `rows`, `rowCount`, and optional `fields`.
|
|
414
458
|
|
|
415
459
|
#### `connect()`
|
|
416
460
|
|
|
@@ -423,75 +467,46 @@ function connect(): Promise<DatabaseConnection>
|
|
|
423
467
|
|
|
424
468
|
**Returns:** A database connection that must be released after use.
|
|
425
469
|
|
|
426
|
-
#### `
|
|
427
|
-
|
|
428
|
-
Counts records matching the given filter conditions, or all records
|
|
429
|
-
if no conditions are specified.
|
|
430
|
-
|
|
431
|
-
```typescript
|
|
432
|
-
function count(table: string, where?: WhereCondition[]): Promise<number>
|
|
433
|
-
```
|
|
434
|
-
|
|
435
|
-
- `table` — The database table name.
|
|
436
|
-
- `where` — Optional filter conditions.
|
|
437
|
-
|
|
438
|
-
**Returns:** The number of matching records.
|
|
439
|
-
|
|
440
|
-
#### `create(table, data)`
|
|
470
|
+
#### `end()`
|
|
441
471
|
|
|
442
|
-
|
|
443
|
-
the number of affected rows (always 1 on success).
|
|
472
|
+
Closes all connections in the bonded pool. Call during graceful shutdown.
|
|
444
473
|
|
|
445
474
|
```typescript
|
|
446
|
-
function
|
|
475
|
+
function end(): Promise<void>
|
|
447
476
|
```
|
|
448
477
|
|
|
449
|
-
|
|
450
|
-
- `data` — The column values to insert as key-value pairs.
|
|
451
|
-
|
|
452
|
-
**Returns:** A `MutationResult` with the inserted row and affected count.
|
|
478
|
+
**Returns:** A promise that resolves when all connections have been closed.
|
|
453
479
|
|
|
454
|
-
#### `
|
|
480
|
+
#### `setStore(store)`
|
|
455
481
|
|
|
456
|
-
|
|
482
|
+
Registers a DataStore implementation as the active singleton. Called by
|
|
483
|
+
bond packages during application startup.
|
|
457
484
|
|
|
458
485
|
```typescript
|
|
459
|
-
function
|
|
460
|
-
table: string,
|
|
461
|
-
id: string | number,
|
|
462
|
-
): Promise<MutationResult<Record<string, unknown>>>
|
|
486
|
+
function setStore(store: DataStore): void
|
|
463
487
|
```
|
|
464
488
|
|
|
465
|
-
- `
|
|
466
|
-
- `id` — The primary key value of the record to delete.
|
|
467
|
-
|
|
468
|
-
**Returns:** A `MutationResult` with the affected count (1 if deleted, 0 if not found).
|
|
489
|
+
- `store` — The DataStore implementation to bond.
|
|
469
490
|
|
|
470
|
-
#### `
|
|
491
|
+
#### `getStore()`
|
|
471
492
|
|
|
472
|
-
|
|
493
|
+
Retrieves the bonded DataStore, throwing if none is configured.
|
|
473
494
|
|
|
474
495
|
```typescript
|
|
475
|
-
function
|
|
476
|
-
table: string,
|
|
477
|
-
where: WhereCondition[],
|
|
478
|
-
): Promise<MutationResult<Record<string, unknown>>>
|
|
496
|
+
function getStore(): DataStore
|
|
479
497
|
```
|
|
480
498
|
|
|
481
|
-
|
|
482
|
-
- `where` — Filter conditions to select records to delete.
|
|
483
|
-
|
|
484
|
-
**Returns:** A `MutationResult` with the number of deleted rows.
|
|
499
|
+
**Returns:** The bonded DataStore implementation.
|
|
485
500
|
|
|
486
|
-
#### `
|
|
501
|
+
#### `hasStore()`
|
|
487
502
|
|
|
488
|
-
|
|
503
|
+
Checks whether a DataStore is currently bonded.
|
|
489
504
|
|
|
490
505
|
```typescript
|
|
491
|
-
function
|
|
506
|
+
function hasStore(): boolean
|
|
492
507
|
```
|
|
493
508
|
|
|
494
|
-
**Returns:**
|
|
509
|
+
**Returns:** `true` if a DataStore is bonded.
|
|
495
510
|
|
|
496
511
|
#### `findById(table, id)`
|
|
497
512
|
|
|
@@ -506,20 +521,6 @@ function findById(table: string, id: string | number): Promise<T | null>
|
|
|
506
521
|
|
|
507
522
|
**Returns:** The matching record cast to `T`, or `null` if not found.
|
|
508
523
|
|
|
509
|
-
#### `findMany(table, options)`
|
|
510
|
-
|
|
511
|
-
Finds multiple records with optional filtering, sorting, pagination,
|
|
512
|
-
and column selection.
|
|
513
|
-
|
|
514
|
-
```typescript
|
|
515
|
-
function findMany(table: string, options?: FindManyOptions): Promise<T[]>
|
|
516
|
-
```
|
|
517
|
-
|
|
518
|
-
- `table` — The database table name.
|
|
519
|
-
- `options` — Query options including `where`, `orderBy`, `limit`, `offset`, and `select`.
|
|
520
|
-
|
|
521
|
-
**Returns:** Array of matching records cast to `T`.
|
|
522
|
-
|
|
523
524
|
#### `findOne(table, where)`
|
|
524
525
|
|
|
525
526
|
Finds a single record matching the given filter conditions. Returns the
|
|
@@ -534,80 +535,47 @@ function findOne(table: string, where: WhereCondition[]): Promise<T | null>
|
|
|
534
535
|
|
|
535
536
|
**Returns:** The matching record cast to `T`, or `null` if none found.
|
|
536
537
|
|
|
537
|
-
#### `
|
|
538
|
-
|
|
539
|
-
Retrieves the bonded database pool, throwing if none is configured.
|
|
540
|
-
|
|
541
|
-
```typescript
|
|
542
|
-
function getPool(): DatabasePool
|
|
543
|
-
```
|
|
544
|
-
|
|
545
|
-
**Returns:** The bonded database pool.
|
|
546
|
-
|
|
547
|
-
#### `getStore()`
|
|
548
|
-
|
|
549
|
-
Retrieves the bonded DataStore, throwing if none is configured.
|
|
550
|
-
|
|
551
|
-
```typescript
|
|
552
|
-
function getStore(): DataStore
|
|
553
|
-
```
|
|
554
|
-
|
|
555
|
-
**Returns:** The bonded DataStore implementation.
|
|
556
|
-
|
|
557
|
-
#### `hasPool()`
|
|
538
|
+
#### `findMany(table, options)`
|
|
558
539
|
|
|
559
|
-
|
|
540
|
+
Finds multiple records with optional filtering, sorting, pagination,
|
|
541
|
+
and column selection.
|
|
560
542
|
|
|
561
543
|
```typescript
|
|
562
|
-
function
|
|
544
|
+
function findMany(table: string, options?: FindManyOptions): Promise<T[]>
|
|
563
545
|
```
|
|
564
546
|
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
#### `hasStore()`
|
|
568
|
-
|
|
569
|
-
Checks whether a DataStore is currently bonded.
|
|
570
|
-
|
|
571
|
-
```typescript
|
|
572
|
-
function hasStore(): boolean
|
|
573
|
-
```
|
|
547
|
+
- `table` — The database table name.
|
|
548
|
+
- `options` — Query options including `where`, `orderBy`, `limit`, `offset`, and `select`.
|
|
574
549
|
|
|
575
|
-
**Returns:**
|
|
550
|
+
**Returns:** Array of matching records cast to `T`.
|
|
576
551
|
|
|
577
|
-
#### `
|
|
552
|
+
#### `count(table, where)`
|
|
578
553
|
|
|
579
|
-
|
|
554
|
+
Counts records matching the given filter conditions, or all records
|
|
555
|
+
if no conditions are specified.
|
|
580
556
|
|
|
581
557
|
```typescript
|
|
582
|
-
function
|
|
558
|
+
function count(table: string, where?: WhereCondition[]): Promise<number>
|
|
583
559
|
```
|
|
584
560
|
|
|
585
|
-
- `
|
|
586
|
-
- `
|
|
561
|
+
- `table` — The database table name.
|
|
562
|
+
- `where` — Optional filter conditions.
|
|
587
563
|
|
|
588
|
-
**Returns:** The
|
|
564
|
+
**Returns:** The number of matching records.
|
|
589
565
|
|
|
590
|
-
#### `
|
|
566
|
+
#### `create(table, data)`
|
|
591
567
|
|
|
592
|
-
|
|
593
|
-
|
|
568
|
+
Inserts a new record into the table. Returns the inserted row and
|
|
569
|
+
the number of affected rows (always 1 on success).
|
|
594
570
|
|
|
595
571
|
```typescript
|
|
596
|
-
function
|
|
572
|
+
function create(table: string, data: Record<string, unknown>): Promise<MutationResult<T>>
|
|
597
573
|
```
|
|
598
574
|
|
|
599
|
-
- `
|
|
600
|
-
|
|
601
|
-
#### `setStore(store)`
|
|
602
|
-
|
|
603
|
-
Registers a DataStore implementation as the active singleton. Called by
|
|
604
|
-
bond packages during application startup.
|
|
605
|
-
|
|
606
|
-
```typescript
|
|
607
|
-
function setStore(store: DataStore): void
|
|
608
|
-
```
|
|
575
|
+
- `table` — The database table name.
|
|
576
|
+
- `data` — The column values to insert as key-value pairs.
|
|
609
577
|
|
|
610
|
-
|
|
578
|
+
**Returns:** A `MutationResult` with the inserted row and affected count.
|
|
611
579
|
|
|
612
580
|
#### `updateById(table, id, data)`
|
|
613
581
|
|
|
@@ -646,12 +614,83 @@ function updateMany(
|
|
|
646
614
|
|
|
647
615
|
**Returns:** A `MutationResult` with the affected count.
|
|
648
616
|
|
|
617
|
+
#### `deleteById(table, id)`
|
|
618
|
+
|
|
619
|
+
Deletes a record identified by its primary key.
|
|
620
|
+
|
|
621
|
+
```typescript
|
|
622
|
+
function deleteById(
|
|
623
|
+
table: string,
|
|
624
|
+
id: string | number,
|
|
625
|
+
): Promise<MutationResult<Record<string, unknown>>>
|
|
626
|
+
```
|
|
627
|
+
|
|
628
|
+
- `table` — The database table name.
|
|
629
|
+
- `id` — The primary key value of the record to delete.
|
|
630
|
+
|
|
631
|
+
**Returns:** A `MutationResult` with the affected count (1 if deleted, 0 if not found).
|
|
632
|
+
|
|
633
|
+
#### `deleteMany(table, where)`
|
|
634
|
+
|
|
635
|
+
Deletes all records matching the given filter conditions.
|
|
636
|
+
|
|
637
|
+
```typescript
|
|
638
|
+
function deleteMany(
|
|
639
|
+
table: string,
|
|
640
|
+
where: WhereCondition[],
|
|
641
|
+
): Promise<MutationResult<Record<string, unknown>>>
|
|
642
|
+
```
|
|
643
|
+
|
|
644
|
+
- `table` — The database table name.
|
|
645
|
+
- `where` — Filter conditions to select records to delete.
|
|
646
|
+
|
|
647
|
+
**Returns:** A `MutationResult` with the number of deleted rows.
|
|
648
|
+
|
|
649
|
+
#### `getActiveTransaction()`
|
|
650
|
+
|
|
651
|
+
The transaction opened by the enclosing `withTransaction()` call, if any.
|
|
652
|
+
Bond pools call this from `query()` and send the statement to the active
|
|
653
|
+
transaction when it is one they opened.
|
|
654
|
+
|
|
655
|
+
```typescript
|
|
656
|
+
function getActiveTransaction(): DatabaseTransaction | undefined
|
|
657
|
+
```
|
|
658
|
+
|
|
659
|
+
**Returns:** The active transaction, or `undefined` outside `withTransaction()`.
|
|
660
|
+
|
|
661
|
+
#### `withTransaction(fn)`
|
|
662
|
+
|
|
663
|
+
Runs `fn` inside one database transaction: commits when it resolves, rolls
|
|
664
|
+
back and rethrows when it throws. Every database call made while `fn` runs
|
|
665
|
+
joins the transaction — `create`/`findMany`/`updateById`/`deleteById`, raw
|
|
666
|
+
`query()`, and the resource packages built on them — so all-or-nothing work
|
|
667
|
+
needs no separate connection and no raw SQL:
|
|
668
|
+
|
|
669
|
+
```ts
|
|
670
|
+
await withTransaction(async () => {
|
|
671
|
+
const order = await create('orders', { userId, total })
|
|
672
|
+
await updateById('products', productId, { stock: stock - 1 })
|
|
673
|
+
})
|
|
674
|
+
```
|
|
675
|
+
|
|
676
|
+
A nested `withTransaction()` joins the outer one. Calls made by unrelated
|
|
677
|
+
concurrent requests do not join it.
|
|
678
|
+
|
|
679
|
+
```typescript
|
|
680
|
+
function withTransaction(fn: () => Promise<T>): Promise<T>
|
|
681
|
+
```
|
|
682
|
+
|
|
683
|
+
- `fn` — The work to run atomically.
|
|
684
|
+
|
|
685
|
+
**Returns:** What `fn` resolves to.
|
|
686
|
+
|
|
649
687
|
## Available Providers
|
|
650
688
|
|
|
651
689
|
| Provider | Package |
|
|
652
690
|
| ------------- | ----------------------------------- |
|
|
653
691
|
| Cloudflare D1 | `@molecule/api-database-d1` |
|
|
654
692
|
| MySQL | `@molecule/api-database-mysql` |
|
|
693
|
+
| PGlite | `@molecule/api-database-pglite` |
|
|
655
694
|
| PostgreSQL | `@molecule/api-database-postgresql` |
|
|
656
695
|
| SQLite | `@molecule/api-database-sqlite` |
|
|
657
696
|
|
|
@@ -688,22 +727,17 @@ Data-access contract — the rules code generators most often get wrong:
|
|
|
688
727
|
query lives on the pool/provider. The store also has NO `.exec()`,
|
|
689
728
|
`.prepare()`, `.run()`, `.get()`, or `.all()` — those are driver methods
|
|
690
729
|
(better-sqlite3 / pg) and calling them fails the type-check.
|
|
691
|
-
- **Atomic multi-write =
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
`
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
those writes committed while the rest rolls back (a half-applied transfer).
|
|
703
|
-
Inside a transaction do every read AND write with `conn.query(sql, values)`
|
|
704
|
-
on that same `conn`, and ALWAYS `release()` in `finally` — a leaked
|
|
705
|
-
connection permanently drains the pool. Prefer this only for true multi-row
|
|
706
|
-
invariants; a single-row update is already atomic via `updateById`.
|
|
730
|
+
- **Atomic multi-write = `withTransaction(async () => { … })`.** When several
|
|
731
|
+
writes must be all-or-nothing (move funds between two accounts, create an
|
|
732
|
+
order AND decrement its stock, accept a booking AND mark the slot taken),
|
|
733
|
+
wrap them: `await withTransaction(async () => { await create('orders', o);
|
|
734
|
+
await updateById('products', id, { stock }) })`. Every call inside — the CRUD
|
|
735
|
+
helpers, `query()`, and the resource packages built on them — joins the one
|
|
736
|
+
transaction; it commits when the callback resolves and rolls back when it
|
|
737
|
+
throws. Never call `pool.transaction()` and then the CRUD helpers: those run
|
|
738
|
+
outside it (Postgres/MySQL: not atomic; SQLite: they wait behind it and fail
|
|
739
|
+
after 30 s). A single-row update is already atomic via `updateById`. D1 has
|
|
740
|
+
no interactive transactions, so `withTransaction` throws there.
|
|
707
741
|
- **Create tables only via timestamped `.sql` files in `migrations/`** (the
|
|
708
742
|
migration runner applies them on startup) — NEVER programmatically through
|
|
709
743
|
the store. Seed rows with `create()`.
|
package/dist/index.d.ts
CHANGED
|
@@ -48,22 +48,17 @@
|
|
|
48
48
|
* query lives on the pool/provider. The store also has NO `.exec()`,
|
|
49
49
|
* `.prepare()`, `.run()`, `.get()`, or `.all()` — those are driver methods
|
|
50
50
|
* (better-sqlite3 / pg) and calling them fails the type-check.
|
|
51
|
-
* - **Atomic multi-write =
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
* `
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
* those writes committed while the rest rolls back (a half-applied transfer).
|
|
63
|
-
* Inside a transaction do every read AND write with `conn.query(sql, values)`
|
|
64
|
-
* on that same `conn`, and ALWAYS `release()` in `finally` — a leaked
|
|
65
|
-
* connection permanently drains the pool. Prefer this only for true multi-row
|
|
66
|
-
* invariants; a single-row update is already atomic via `updateById`.
|
|
51
|
+
* - **Atomic multi-write = `withTransaction(async () => { … })`.** When several
|
|
52
|
+
* writes must be all-or-nothing (move funds between two accounts, create an
|
|
53
|
+
* order AND decrement its stock, accept a booking AND mark the slot taken),
|
|
54
|
+
* wrap them: `await withTransaction(async () => { await create('orders', o);
|
|
55
|
+
* await updateById('products', id, { stock }) })`. Every call inside — the CRUD
|
|
56
|
+
* helpers, `query()`, and the resource packages built on them — joins the one
|
|
57
|
+
* transaction; it commits when the callback resolves and rolls back when it
|
|
58
|
+
* throws. Never call `pool.transaction()` and then the CRUD helpers: those run
|
|
59
|
+
* outside it (Postgres/MySQL: not atomic; SQLite: they wait behind it and fail
|
|
60
|
+
* after 30 s). A single-row update is already atomic via `updateById`. D1 has
|
|
61
|
+
* no interactive transactions, so `withTransaction` throws there.
|
|
67
62
|
* - **Create tables only via timestamped `.sql` files in `migrations/`** (the
|
|
68
63
|
* migration runner applies them on startup) — NEVER programmatically through
|
|
69
64
|
* the store. Seed rows with `create()`.
|
|
@@ -90,4 +85,5 @@ export * from './types.js';
|
|
|
90
85
|
export * from './provider.js';
|
|
91
86
|
export * from './store.js';
|
|
92
87
|
export * from './store-provider.js';
|
|
88
|
+
export * from './transaction-context.js';
|
|
93
89
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiFG;AAGH,cAAc,oBAAoB,CAAA;AAClC,cAAc,YAAY,CAAA;AAG1B,cAAc,eAAe,CAAA;AAG7B,cAAc,YAAY,CAAA;AAC1B,cAAc,qBAAqB,CAAA;AACnC,cAAc,0BAA0B,CAAA"}
|
package/dist/index.js
CHANGED
|
@@ -48,22 +48,17 @@
|
|
|
48
48
|
* query lives on the pool/provider. The store also has NO `.exec()`,
|
|
49
49
|
* `.prepare()`, `.run()`, `.get()`, or `.all()` — those are driver methods
|
|
50
50
|
* (better-sqlite3 / pg) and calling them fails the type-check.
|
|
51
|
-
* - **Atomic multi-write =
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
* `
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
* those writes committed while the rest rolls back (a half-applied transfer).
|
|
63
|
-
* Inside a transaction do every read AND write with `conn.query(sql, values)`
|
|
64
|
-
* on that same `conn`, and ALWAYS `release()` in `finally` — a leaked
|
|
65
|
-
* connection permanently drains the pool. Prefer this only for true multi-row
|
|
66
|
-
* invariants; a single-row update is already atomic via `updateById`.
|
|
51
|
+
* - **Atomic multi-write = `withTransaction(async () => { … })`.** When several
|
|
52
|
+
* writes must be all-or-nothing (move funds between two accounts, create an
|
|
53
|
+
* order AND decrement its stock, accept a booking AND mark the slot taken),
|
|
54
|
+
* wrap them: `await withTransaction(async () => { await create('orders', o);
|
|
55
|
+
* await updateById('products', id, { stock }) })`. Every call inside — the CRUD
|
|
56
|
+
* helpers, `query()`, and the resource packages built on them — joins the one
|
|
57
|
+
* transaction; it commits when the callback resolves and rolls back when it
|
|
58
|
+
* throws. Never call `pool.transaction()` and then the CRUD helpers: those run
|
|
59
|
+
* outside it (Postgres/MySQL: not atomic; SQLite: they wait behind it and fail
|
|
60
|
+
* after 30 s). A single-row update is already atomic via `updateById`. D1 has
|
|
61
|
+
* no interactive transactions, so `withTransaction` throws there.
|
|
67
62
|
* - **Create tables only via timestamped `.sql` files in `migrations/`** (the
|
|
68
63
|
* migration runner applies them on startup) — NEVER programmatically through
|
|
69
64
|
* the store. Seed rows with `create()`.
|
|
@@ -93,4 +88,5 @@ export * from './provider.js';
|
|
|
93
88
|
// DataStore exports (abstract CRUD)
|
|
94
89
|
export * from './store.js';
|
|
95
90
|
export * from './store-provider.js';
|
|
91
|
+
export * from './transaction-context.js';
|
|
96
92
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiFG;AAEH,eAAe;AACf,cAAc,oBAAoB,CAAA;AAClC,cAAc,YAAY,CAAA;AAE1B,sCAAsC;AACtC,cAAc,eAAe,CAAA;AAE7B,oCAAoC;AACpC,cAAc,YAAY,CAAA;AAC1B,cAAc,qBAAqB,CAAA;AACnC,cAAc,0BAA0B,CAAA"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `withTransaction(fn)`: every database call made while `fn` runs — the CRUD
|
|
3
|
+
* helpers (`create`, `findMany`, `updateById`, …) and `query()` alike — joins
|
|
4
|
+
* one transaction, on any bond that supports interactive transactions.
|
|
5
|
+
*
|
|
6
|
+
* Without it, the CRUD helpers run on the pool and commit on their own, so
|
|
7
|
+
* calling them between `BEGIN` and `COMMIT` is either quietly not atomic
|
|
8
|
+
* (Postgres, MySQL: a failure leaves half the writes committed) or a deadlock
|
|
9
|
+
* (SQLite: the open transaction holds the single connection, and the helper's
|
|
10
|
+
* query waits behind it forever).
|
|
11
|
+
*
|
|
12
|
+
* @module
|
|
13
|
+
*/
|
|
14
|
+
import type { DatabaseTransaction } from './types.js';
|
|
15
|
+
/**
|
|
16
|
+
* The transaction opened by the enclosing `withTransaction()` call, if any.
|
|
17
|
+
* Bond pools call this from `query()` and send the statement to the active
|
|
18
|
+
* transaction when it is one they opened.
|
|
19
|
+
*
|
|
20
|
+
* @returns The active transaction, or `undefined` outside `withTransaction()`.
|
|
21
|
+
*/
|
|
22
|
+
export declare const getActiveTransaction: () => DatabaseTransaction | undefined;
|
|
23
|
+
/**
|
|
24
|
+
* Runs `fn` inside one database transaction: commits when it resolves, rolls
|
|
25
|
+
* back and rethrows when it throws. Every database call made while `fn` runs
|
|
26
|
+
* joins the transaction — `create`/`findMany`/`updateById`/`deleteById`, raw
|
|
27
|
+
* `query()`, and the resource packages built on them — so all-or-nothing work
|
|
28
|
+
* needs no separate connection and no raw SQL:
|
|
29
|
+
*
|
|
30
|
+
* ```ts
|
|
31
|
+
* await withTransaction(async () => {
|
|
32
|
+
* const order = await create('orders', { userId, total })
|
|
33
|
+
* await updateById('products', productId, { stock: stock - 1 })
|
|
34
|
+
* })
|
|
35
|
+
* ```
|
|
36
|
+
*
|
|
37
|
+
* A nested `withTransaction()` joins the outer one. Calls made by unrelated
|
|
38
|
+
* concurrent requests do not join it.
|
|
39
|
+
*
|
|
40
|
+
* @param fn - The work to run atomically.
|
|
41
|
+
* @returns What `fn` resolves to.
|
|
42
|
+
* @throws {Error} If the bonded database has no interactive transactions
|
|
43
|
+
* (Cloudflare D1), or rethrows what `fn` throws after rolling back.
|
|
44
|
+
*/
|
|
45
|
+
export declare const withTransaction: <T>(fn: () => Promise<T>) => Promise<T>;
|
|
46
|
+
//# sourceMappingURL=transaction-context.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transaction-context.d.ts","sourceRoot":"","sources":["../src/transaction-context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAKH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAA;AAgBrD;;;;;;GAMG;AACH,eAAO,MAAM,oBAAoB,QAAO,mBAAmB,GAAG,SAA+B,CAAA;AAE7F;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,eAAe,GAAU,CAAC,EAAE,IAAI,MAAM,OAAO,CAAC,CAAC,CAAC,KAAG,OAAO,CAAC,CAAC,CA4BxE,CAAA"}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `withTransaction(fn)`: every database call made while `fn` runs — the CRUD
|
|
3
|
+
* helpers (`create`, `findMany`, `updateById`, …) and `query()` alike — joins
|
|
4
|
+
* one transaction, on any bond that supports interactive transactions.
|
|
5
|
+
*
|
|
6
|
+
* Without it, the CRUD helpers run on the pool and commit on their own, so
|
|
7
|
+
* calling them between `BEGIN` and `COMMIT` is either quietly not atomic
|
|
8
|
+
* (Postgres, MySQL: a failure leaves half the writes committed) or a deadlock
|
|
9
|
+
* (SQLite: the open transaction holds the single connection, and the helper's
|
|
10
|
+
* query waits behind it forever).
|
|
11
|
+
*
|
|
12
|
+
* @module
|
|
13
|
+
*/
|
|
14
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
15
|
+
import { getPool } from './provider.js';
|
|
16
|
+
const STORAGE_KEY = Symbol.for('@molecule/api-database/transaction-context');
|
|
17
|
+
/**
|
|
18
|
+
* One storage per process, even if two copies of this package are installed:
|
|
19
|
+
* the bond and the application must see the same active transaction.
|
|
20
|
+
*/
|
|
21
|
+
const storage = (() => {
|
|
22
|
+
const holder = globalThis;
|
|
23
|
+
holder[STORAGE_KEY] ??= new AsyncLocalStorage();
|
|
24
|
+
return holder[STORAGE_KEY];
|
|
25
|
+
})();
|
|
26
|
+
/**
|
|
27
|
+
* The transaction opened by the enclosing `withTransaction()` call, if any.
|
|
28
|
+
* Bond pools call this from `query()` and send the statement to the active
|
|
29
|
+
* transaction when it is one they opened.
|
|
30
|
+
*
|
|
31
|
+
* @returns The active transaction, or `undefined` outside `withTransaction()`.
|
|
32
|
+
*/
|
|
33
|
+
export const getActiveTransaction = () => storage.getStore();
|
|
34
|
+
/**
|
|
35
|
+
* Runs `fn` inside one database transaction: commits when it resolves, rolls
|
|
36
|
+
* back and rethrows when it throws. Every database call made while `fn` runs
|
|
37
|
+
* joins the transaction — `create`/`findMany`/`updateById`/`deleteById`, raw
|
|
38
|
+
* `query()`, and the resource packages built on them — so all-or-nothing work
|
|
39
|
+
* needs no separate connection and no raw SQL:
|
|
40
|
+
*
|
|
41
|
+
* ```ts
|
|
42
|
+
* await withTransaction(async () => {
|
|
43
|
+
* const order = await create('orders', { userId, total })
|
|
44
|
+
* await updateById('products', productId, { stock: stock - 1 })
|
|
45
|
+
* })
|
|
46
|
+
* ```
|
|
47
|
+
*
|
|
48
|
+
* A nested `withTransaction()` joins the outer one. Calls made by unrelated
|
|
49
|
+
* concurrent requests do not join it.
|
|
50
|
+
*
|
|
51
|
+
* @param fn - The work to run atomically.
|
|
52
|
+
* @returns What `fn` resolves to.
|
|
53
|
+
* @throws {Error} If the bonded database has no interactive transactions
|
|
54
|
+
* (Cloudflare D1), or rethrows what `fn` throws after rolling back.
|
|
55
|
+
*/
|
|
56
|
+
export const withTransaction = async (fn) => {
|
|
57
|
+
if (storage.getStore())
|
|
58
|
+
return fn();
|
|
59
|
+
const pool = getPool();
|
|
60
|
+
if (!pool.transaction) {
|
|
61
|
+
throw new Error('withTransaction(): the bonded database has no interactive transactions (Cloudflare D1). Group the writes into one batch instead.');
|
|
62
|
+
}
|
|
63
|
+
const tx = await pool.transaction();
|
|
64
|
+
let result;
|
|
65
|
+
try {
|
|
66
|
+
result = await storage.run(tx, fn);
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
try {
|
|
70
|
+
await tx.rollback();
|
|
71
|
+
}
|
|
72
|
+
catch (rollbackError) {
|
|
73
|
+
// Both failures matter: the work's error says why, the rollback's says the
|
|
74
|
+
// connection may still hold the transaction.
|
|
75
|
+
throw new AggregateError([error, rollbackError], 'withTransaction(): the work failed and so did the rollback', { cause: rollbackError });
|
|
76
|
+
}
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
await tx.commit();
|
|
80
|
+
return result;
|
|
81
|
+
};
|
|
82
|
+
//# sourceMappingURL=transaction-context.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transaction-context.js","sourceRoot":"","sources":["../src/transaction-context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAA;AAEpD,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAA;AAGvC,MAAM,WAAW,GAAG,MAAM,CAAC,GAAG,CAAC,4CAA4C,CAAC,CAAA;AAE5E;;;GAGG;AACH,MAAM,OAAO,GAA2C,CAAC,GAAG,EAAE;IAC5D,MAAM,MAAM,GAAG,UAEd,CAAA;IACD,MAAM,CAAC,WAAW,CAAC,KAAK,IAAI,iBAAiB,EAAuB,CAAA;IACpE,OAAO,MAAM,CAAC,WAAW,CAAC,CAAA;AAC5B,CAAC,CAAC,EAAE,CAAA;AAEJ;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,GAAoC,EAAE,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAA;AAE7F;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,KAAK,EAAK,EAAoB,EAAc,EAAE;IAC3E,IAAI,OAAO,CAAC,QAAQ,EAAE;QAAE,OAAO,EAAE,EAAE,CAAA;IACnC,MAAM,IAAI,GAAG,OAAO,EAAE,CAAA;IACtB,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC;QACtB,MAAM,IAAI,KAAK,CACb,kIAAkI,CACnI,CAAA;IACH,CAAC;IACD,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,WAAW,EAAE,CAAA;IACnC,IAAI,MAAS,CAAA;IACb,IAAI,CAAC;QACH,MAAM,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,CAAC,CAAA;IACpC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC;YACH,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAA;QACrB,CAAC;QAAC,OAAO,aAAa,EAAE,CAAC;YACvB,2EAA2E;YAC3E,6CAA6C;YAC7C,MAAM,IAAI,cAAc,CACtB,CAAC,KAAK,EAAE,aAAa,CAAC,EACtB,4DAA4D,EAC5D,EAAE,KAAK,EAAE,aAAa,EAAE,CACzB,CAAA;QACH,CAAC;QACD,MAAM,KAAK,CAAA;IACb,CAAC;IACD,MAAM,EAAE,CAAC,MAAM,EAAE,CAAA;IACjB,OAAO,MAAM,CAAA;AACf,CAAC,CAAA"}
|