@molecule/api-database 1.0.2 → 1.1.0
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 +51 -17
- 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-15T12:34:32.789Z
|
|
7
7
|
-->
|
|
8
8
|
|
|
9
9
|
# @molecule/api-database
|
|
@@ -534,6 +534,18 @@ function findOne(table: string, where: WhereCondition[]): Promise<T | null>
|
|
|
534
534
|
|
|
535
535
|
**Returns:** The matching record cast to `T`, or `null` if none found.
|
|
536
536
|
|
|
537
|
+
#### `getActiveTransaction()`
|
|
538
|
+
|
|
539
|
+
The transaction opened by the enclosing `withTransaction()` call, if any.
|
|
540
|
+
Bond pools call this from `query()` and send the statement to the active
|
|
541
|
+
transaction when it is one they opened.
|
|
542
|
+
|
|
543
|
+
```typescript
|
|
544
|
+
function getActiveTransaction(): DatabaseTransaction | undefined
|
|
545
|
+
```
|
|
546
|
+
|
|
547
|
+
**Returns:** The active transaction, or `undefined` outside `withTransaction()`.
|
|
548
|
+
|
|
537
549
|
#### `getPool()`
|
|
538
550
|
|
|
539
551
|
Retrieves the bonded database pool, throwing if none is configured.
|
|
@@ -646,12 +658,39 @@ function updateMany(
|
|
|
646
658
|
|
|
647
659
|
**Returns:** A `MutationResult` with the affected count.
|
|
648
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"}
|