Repository navigation
Expand file tree
/
Copy pathdatabase.ts
More file actions
1070 lines (999 loc) · 46.8 KB
/
Copy pathdatabase.ts
File metadata and controls
1070 lines (999 loc) · 46.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Executing compiled statements, and transactions over them.
//
// The library still never opens a connection: a `Database` is built from the
// `SqlClient` the caller already has. Transactions are Effect's own
// `withTransaction`, which pins the connection through fiber context, plus what
// it does not do: settings, typed COMMIT/ROLLBACK failures, a guard against
// statements outliving their transaction, and contention retry. See
// `design/transactions.md`.
import { Array as Arr, Cause, Context, Effect, ErrorReporter, Exit, Layer, Option, References, Schedule, Schema, Stream } from "effect"
import { dual } from "effect/Function"
import * as SqlClient from "effect/sql/SqlClient"
import { isSqlError } from "effect/sql/SqlError"
import { compileCH, compileUnion, type CompiledQueryDecodeError, type CompiledQuery } from "../ch/compile"
import { decodeErrorFromCause } from "../ch/decode-error"
import { noTransactions, type Dialect, type IsolationLevel, type TransactionSettings } from "../ch/dialect"
import type { QueryBuilderError } from "../ch/errors"
import { fillDefaults, type RequirementsOf } from "../ch/client-defaults"
import type { AnyInsert } from "../ch/insert"
import type { CHDelete, CHUpdate } from "../ch/update"
import type { CHQuery, NeedsSelect } from "../ch/query"
import type { CHUnionQuery, QueryParams } from "../ch/union"
import type { DialectSatisfied, ParamsSatisfied, SourcesSatisfied } from "../ch/expr"
import {
DatabaseError,
ResultCardinalityError,
TransactionClosed,
TransactionCommitFailed,
TransactionOptionsRejected,
TenantScopeViolation,
TransactionRollbackFailed,
TransactionUnsupported,
type TransactionError,
} from "./errors"
import { isSqlTemplate, renderTemplate, type SqlTemplate } from "./sql"
import { errorCodeOf, firstLine, reasonOf, sqlStateOf, toDatabaseError } from "./sql-error"
import { traceBatch, traceStatement, traceStream, type StatementObservation, type TraceOptions, type TracedStatement } from "./tracing"
/** SQL and the values bound to its placeholders. A `CompiledQuery` is one. */
export interface Statement {
readonly sql: string
readonly parameters?: ReadonlyArray<unknown>
/**
* The indexes in `parameters` of values that must not reach a span or a log:
* those given as `Redacted`. Set by `compile` and by `sql\`...\``.
*/
readonly sensitiveParameters?: ReadonlyArray<number>
}
/** What `query` and `execute` take: a `sql\`...\`` template, or SQL with its parameters. */
export type StatementInput = SqlTemplate | Statement
/** What `run` takes: a built query, a union, an insert, or one already compiled. */
export type Runnable =
| CHQuery<any, any, any, any>
| CHUnionQuery<any>
| AnyInsert
| CHUpdate<any, any, any, "ready", never, any, any>
| CHDelete<any, any>
| CompiledQuery<any, any>
/**
* What `runWrite` takes: an insert, update or delete with no `returning`.
* A write with RETURNING gives its rows to `run` instead.
*/
export type Write = AnyInsert<never> | CHUpdate<any, any, never, "ready", never, any, any> | CHDelete<any, never>
/**
* What a write did, as the server counted it. See docs/database.md#write-results.
*/
export interface WriteResult {
/**
* The rows the statement wrote, as the server counts them. Through mysql2,
* which connects with `CLIENT_FOUND_ROWS`, an UPDATE counts every row it
* matched, including those it left as they were; an
* `ON DUPLICATE KEY UPDATE` counts 2 for a row it updated, and 1 for a row
* inserted or matched and left as it was.
*/
readonly affectedRows: number
/**
* The key of the row an insert wrote: MySQL's `AUTO_INCREMENT` value of the
* first row, generated or given explicitly (of the existing row, for an
* `ON DUPLICATE KEY UPDATE` that updated one), SQLite's and D1's rowid of the
* last. `undefined` for an update or delete, a MySQL insert into a table with
* no `AUTO_INCREMENT` column, a SQLite or D1 `onConflictDoUpdate`, and always
* on Postgres, where `returning` reads it.
*/
readonly insertId: number | undefined
}
/**
* `unknown` when a `Runnable` can run as it is. A query with no SELECT list
* cannot; a write without `where`/`allRows` is not a `Runnable` at all.
*/
export type RunCheck<Q> = Q extends CHQuery<any, infer Output, any, any> ? NeedsSelect<Output> : unknown
/** The decoded row of a `Runnable`. */
export type RowOf<Q> =
Q extends CompiledQuery<infer Output, any> ? Output : Q extends { readonly _phantom?: { output: infer Output } } ? Output : never
/**
* `unknown` when every statement of a batch can run as `run` would take it;
* otherwise the first refusal (a missing param, a function of another
* dialect, a query with no SELECT list), naming the statement's position.
*/
export type BatchCheck<Qs extends ReadonlyArray<Runnable>, Given, Functions extends string> = number extends Qs["length"]
? // An array, not a tuple: its indexes are `number`, so check its element type as one statement.
StatementCheck<Qs[number], Given, Functions> extends infer Check
? unknown extends Check
? unknown
: { readonly batchStatementRefused: { readonly statement: number; readonly refused: Check } }
: unknown
: { readonly [K in keyof Qs]: StatementCheck<Qs[K], Given, Functions> } extends infer Checks
? FirstRefusal<Checks>
: unknown
/** What `run` checks of one statement. */
type StatementCheck<Q, Given, Functions extends string> = RunCheck<Q> &
ParamsSatisfied<QueryParams<Q>, Given> &
DialectSatisfied<QueryParams<Q>, Functions> &
SourcesSatisfied<QueryParams<Q>>
type FirstRefusal<Checks> = {
readonly [K in keyof Checks]: unknown extends Checks[K] ? never : { readonly statement: K; readonly refused: Checks[K] }
}[keyof Checks & `${number}`] extends infer R
? [R] extends [never]
? unknown
: { readonly batchStatementRefused: R }
: unknown
/** The decoded rows of each statement of a batch, in order. */
export type BatchRows<Qs extends ReadonlyArray<Runnable>> = { -readonly [K in keyof Qs]: ReadonlyArray<RowOf<Qs[K]>> }
/** A row codec for `query`. */
export type RowSchema<A> = Schema.Codec<A, unknown, never, never>
export interface RetryOptions {
/** Retries after the first attempt. Default 3. */
readonly times?: number
/** Delay between attempts. Default exponential from 50 ms. */
readonly schedule?: Schedule.Schedule<unknown>
}
export interface TransactionOptions extends TransactionSettings {
/**
* Re-run the whole transaction, with a fresh BEGIN, on a serialization
* failure or deadlock. Outermost transaction only. `"contention"` uses the
* defaults of `retryContention`.
*/
readonly retry?: "contention" | RetryOptions | undefined
}
/** The open transaction, as `Transaction` describes it inside the body. */
export interface TransactionInfo {
/** 0 for the outermost transaction, 1 for its first savepoint, ... */
readonly depth: number
/** What the outermost transaction set; `undefined` is the server default. */
readonly isolationLevel: IsolationLevel | undefined
readonly accessMode: "read write" | "read only" | undefined
}
/**
* The open transaction. Present only inside `transaction`, which also removes
* it from the requirements of its body. `requireTransaction` adds it, which is
* how a helper says it must run inside a transaction. Read it for the depth or
* the settings of the transaction you are in.
*/
export class Transaction extends Context.Service<Transaction, TransactionInfo>()("@maple-dev/effect-orm/Transaction") {}
/**
* A database. `Functions` is its dialect's function set (`"postgres"` for a
* `Database` built with `postgresDialect`): `run` refuses, in the type, a query
* that uses another set's functions. `string`, the `Database` in context, does
* not check the set, only that a query does not mix two.
*/
export interface DatabaseApi<Functions extends string = string> {
readonly dialect: Dialect<Functions>
/**
* Compile a query for this database's dialect, run it, and decode its rows.
* A write returns its RETURNING rows, or none without `returning`.
* `params` fills the query's `param.*` markers. A query compiled elsewhere
* runs as it is, if it was compiled for this dialect. A write first runs
* its table's client defaults (`fillDefaults`), so it requires what they need.
*/
readonly run: <Q extends Runnable, const Given extends object = {}>(
query: Q &
RunCheck<Q> &
ParamsSatisfied<QueryParams<Q>, Given> &
DialectSatisfied<QueryParams<Q>, Functions> &
SourcesSatisfied<QueryParams<Q>>,
params?: Given,
) => Effect.Effect<ReadonlyArray<RowOf<Q>>, DatabaseError | QueryBuilderError | CompiledQueryDecodeError, RequirementsOf<Q>>
/**
* `run` as a stream: rows come out one at a time, each decoded by the
* query's row schema, so a large result never has to fit in memory. The
* statement is sent when the stream runs, and again each time it runs.
* Rows arrive as the driver reads them: a cursor where the driver has one,
* otherwise the whole result first. A write runs its client defaults first,
* as `run` does.
*/
/**
* Run a fixed list of statements as one atomic unit and decode each one's
* rows: a tuple, in order. On D1 it is one `batch` request (D1 has no
* transactions); elsewhere it runs the statements in a transaction (a
* savepoint inside an open one). `params` fills every statement's `param.*`
* markers. Each write first runs its table's client defaults, as `run` does.
* A dialect with neither fails with `TransactionUnsupported`.
*/
readonly batch: <const Qs extends ReadonlyArray<Runnable>, const Given extends object = {}>(
queries: Qs & BatchCheck<Qs, Given, Functions>,
params?: Given,
) => Effect.Effect<BatchRows<Qs>, DatabaseError | QueryBuilderError | CompiledQueryDecodeError | TransactionError, RequirementsOf<Qs[number]>>
readonly stream: <Q extends Runnable, const Given extends object = {}>(
query: Q &
RunCheck<Q> &
ParamsSatisfied<QueryParams<Q>, Given> &
DialectSatisfied<QueryParams<Q>, Functions> &
SourcesSatisfied<QueryParams<Q>>,
params?: Given,
) => Stream.Stream<RowOf<Q>, DatabaseError | QueryBuilderError | CompiledQueryDecodeError, RequirementsOf<Q>>
/**
* Run an insert, update or delete and return what it did: the rows it
* changed and, for an insert, the key it generated. A write first runs its
* table's client defaults, as `run` does. ClickHouse reports neither, so a
* write there is refused before it is sent.
*/
readonly runWrite: <Q extends Write, const Given extends object = {}>(
query: Q &
ParamsSatisfied<QueryParams<Q>, Given> &
DialectSatisfied<QueryParams<Q>, Functions> &
SourcesSatisfied<QueryParams<Q>>,
params?: Given,
) => Effect.Effect<WriteResult, DatabaseError | QueryBuilderError, RequirementsOf<Q>>
/** Run a statement and return its rows, decoded through `schema` when given. */
readonly query: {
(statement: StatementInput): Effect.Effect<ReadonlyArray<Record<string, unknown>>, DatabaseError>
<A>(statement: StatementInput, schema: RowSchema<A>): Effect.Effect<ReadonlyArray<A>, DatabaseError | CompiledQueryDecodeError>
}
/** Run a statement whose rows are not wanted: DDL, an advisory lock, a write without RETURNING. */
readonly execute: (statement: StatementInput) => Effect.Effect<void, DatabaseError>
/**
* Run `body` in a transaction. Nested calls become savepoints. A failure,
* defect or interruption in `body` rolls back; domain errors pass through
* unchanged.
*/
readonly transaction: <A, E, R>(
body: Effect.Effect<A, E, R>,
options?: TransactionOptions,
) => Effect.Effect<A, E | DatabaseError | TransactionError, Exclude<R, Transaction>>
/**
* Re-run `effect` when it fails with a serialization failure or deadlock
* (SQLSTATE 40001 / 40P01), including one found at COMMIT. Domain errors are
* never retried. Inside an open transaction it refuses, because only the
* outermost transaction can start again.
*/
readonly retryContention: <A, E, R>(
effect: Effect.Effect<A, E, R>,
options?: RetryOptions,
) => Effect.Effect<A, E | TransactionOptionsRejected, R>
}
export class Database extends Context.Service<Database, DatabaseApi>()("@maple-dev/effect-orm/Database") {}
export interface FromSqlClientOptions<Functions extends string = string> {
/** The dialect the database speaks: `clickhouseDialect`, `postgresDialect`, `sqliteDialect`, `d1Dialect`, `mysqlDialect` or `mariadbDialect`. */
readonly dialect: Dialect<Functions>
/**
* Wraps statements run by `execute`. Pass the ClickHouse client's
* `asCommand`, whose query path asks for a JSON result a DDL statement does
* not have; leave unset for Postgres.
*/
readonly command?: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>
/**
* Called with every statement before it runs, including the `BEGIN ...`
* (effect 4.0.6 and later) or `SET TRANSACTION` a transaction's settings
* become. For collecting statements into one span or log line per request.
*/
readonly observe?: (statement: Statement) => Effect.Effect<void>
/**
* Keep the SQL driver's own span inside each statement span. Off by default:
* the statement span already carries the query text, so the driver's span is
* a second span per statement with nothing new. Turn it on to also get what
* only the driver records, such as `server.address` or connection waits.
*/
readonly driverSpans?: boolean
/**
* Called with every statement once it has ended: its names, duration, row
* count or `error.type`. Values given as `Redacted` stay `Redacted` in its
* `parameters`. For metrics, slow-query logs, or a statement collector.
*/
readonly observeExit?: (observation: StatementObservation) => Effect.Effect<void>
/**
* Put each bound value on the statement span as
* `db.query.parameter.<index>`, as the OpenTelemetry conventions allow. Off
* by default, so spans carry no values. A value given as `Redacted` is
* written `<redacted>`.
*/
readonly spanParameters?: boolean
/**
* Refuse, as a `TenantScopeViolation` defect, any compiled statement whose
* `tenantScope` is `"cross-tenant"` unless it was declared with
* `.crossTenant()`. Off by default. Plain SQL given to `query` and
* `execute` has no scope to check and is not refused; see
* docs/tenant-scoping.md.
*/
readonly requireTenantScope?: boolean
}
// Whether the transaction a fiber's context belongs to is still open. Keyed by
// client so a closed transaction on one database does not flag another.
interface OpenState {
open: boolean
readonly client: SqlClient.SqlClient
}
/** @internal — also read by `resolver.ts` to keep batches inside one transaction. */
export class TransactionOpen extends Context.Service<TransactionOpen, OpenState>()("@maple-dev/effect-orm/TransactionOpen") {}
// A defect from the body, carried through `withTransaction` as a failure so the
// transaction still rolls back and any defect that comes out of it is known to
// be COMMIT's or ROLLBACK's.
class BodyDefect {
readonly _tag = "@maple-dev/effect-orm/BodyDefect"
constructor(readonly cause: Cause.Cause<unknown>) {}
}
const CONTENTION_REASONS = new Set(["SerializationError", "DeadlockError"])
const CONTENTION_STATES = new Set(["40001", "40P01"])
/** A serialization failure or deadlock: safe to replay as a fresh transaction. */
export const isContention = (error: unknown): boolean =>
(error instanceof DatabaseError || error instanceof TransactionCommitFailed) &&
(CONTENTION_REASONS.has(error.reason) || (error.sqlState !== undefined && CONTENTION_STATES.has(error.sqlState)))
const settingsOf = (options: TransactionOptions): TransactionSettings => ({
isolationLevel: options.isolationLevel,
accessMode: options.accessMode,
deferrable: options.deferrable,
})
const hasSettings = (settings: TransactionSettings): boolean =>
settings.isolationLevel !== undefined || settings.accessMode !== undefined || settings.deferrable !== undefined
const committed = (state: OpenState) =>
Effect.sync(() => {
state.open = false
})
/** A `Database` over an Effect `SqlClient`, typed with its dialect's function set. */
export const fromSqlClient = <Functions extends string = string>(
sql: SqlClient.SqlClient,
options: FromSqlClientOptions<Functions>,
): DatabaseApi<Functions> => {
const { dialect } = options
const capabilities = dialect.transactions ?? noTransactions
const command = options.command ?? ((effect) => effect)
const observe = options.observe ?? (() => Effect.void)
// The statement span is the span: the driver's own runs untraced unless asked for.
const driver = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
options.driverSpans === true ? effect : Effect.withTracerEnabled(effect, false)
const driverStream = <A, E, R>(stream: Stream.Stream<A, E, R>): Stream.Stream<A, E, R> =>
options.driverSpans === true ? stream : Stream.provideService(stream, References.TracerEnabled, false)
const traceOptions: TraceOptions = { spanParameters: options.spanParameters, observeExit: options.observeExit }
// Result names exactly as the server sent them: the compiled decoder reads
// the aliases it wrote.
const raw = sql.withoutTransforms()
// A statement carrying the context of a transaction that has ended would run
// on a connection already back in the pool. That is a bug (a fiber forked in
// the transaction and never joined), so it is a defect, not an error to handle.
const guard = (statement: Statement) =>
Effect.flatMap(Effect.serviceOption(TransactionOpen), (state) =>
Option.isSome(state) && state.value.client === sql && !state.value.open
? Effect.die(
new TransactionClosed({
message: "a statement ran after its transaction ended; join fibers forked inside a transaction before it returns",
sql: statement.sql,
}),
)
: observe(statement),
)
// A plain Statement has no scope, so only a compiled one can be refused.
const checkScope = <S extends Statement & Partial<Pick<CompiledQuery<unknown>, "tenantScope" | "crossTenantDeclared">>>(
statement: S,
): Effect.Effect<S> =>
options.requireTenantScope === true && statement.tenantScope === "cross-tenant" && statement.crossTenantDeclared !== true
? Effect.die(
new TenantScopeViolation({
message:
"this statement is not confined to one tenant; filter the tenant column with eq or a one-value in_, or declare it with .crossTenant()",
sql: statement.sql,
}),
)
: Effect.succeed(statement)
const resolve = (statement: StatementInput): Effect.Effect<Statement, DatabaseError> =>
isSqlTemplate(statement) ? renderTemplate(statement, dialect) : checkScope(statement)
const rows = (statement: Statement & TracedStatement) =>
traceStatement(
dialect,
statement,
guard(statement).pipe(
Effect.andThen(driver(raw.unsafe<Record<string, unknown>>(statement.sql, statement.parameters ?? []))),
Effect.map((rows): ReadonlyArray<Record<string, unknown>> => rows),
Effect.mapError(toDatabaseError(statement.sql)),
),
(rows) => rows.length,
traceOptions,
)
const decodeWith =
<A>(schema: RowSchema<A>) =>
(wire: ReadonlyArray<Record<string, unknown>>) => {
const decode = Schema.decodeUnknownEffect(schema)
return Effect.forEach(wire, (row, rowIndex) =>
decode(row).pipe(
Effect.mapError(
(cause) =>
decodeErrorFromCause({
prefix: `row ${rowIndex} did not match the schema`,
rowIndex,
cause,
dialect: dialect.name,
}),
),
),
)
}
const query = ((statement: StatementInput, schema?: RowSchema<unknown>) =>
Effect.flatMap(
resolve(statement),
(resolved): Effect.Effect<ReadonlyArray<unknown>, DatabaseError | CompiledQueryDecodeError> =>
schema === undefined ? rows(resolved) : Effect.flatMap(rows(resolved), decodeWith(schema)),
)) as DatabaseApi["query"]
const execute: DatabaseApi["execute"] = (statement) =>
Effect.flatMap(resolve(statement), (resolved: Statement & TracedStatement) =>
traceStatement(
dialect,
resolved,
guard(resolved).pipe(
Effect.andThen(driver(command(raw.unsafe(resolved.sql, resolved.parameters ?? [])))),
Effect.asVoid,
Effect.mapError(toDatabaseError(resolved.sql)),
),
undefined,
traceOptions,
),
)
const compileFor = (
runnable: Runnable,
params: Record<string, unknown>,
): Effect.Effect<CompiledQuery<any, any>, QueryBuilderError> => {
if ("decodeRows" in runnable) {
return runnable.dialect !== undefined && runnable.dialect !== dialect.name
? Effect.die(
new DatabaseError({
message: `a query compiled for ${runnable.dialect} cannot run on a ${dialect.name} database; pass the query to run instead of compiling it`,
sql: runnable.sql,
reason: "DialectMismatch",
cause: undefined,
}),
)
: Effect.succeed(runnable)
}
if ("_tag" in runnable && runnable._tag === "CHUnionQuery") return compileUnion(runnable, params, { dialect })
if ("_tag" in runnable && (runnable._tag === "CHInsert" || runnable._tag === "CHUpdate" || runnable._tag === "CHDelete")) {
return compileCH(runnable, params, { dialect })
}
return compileCH(runnable as CHQuery<any, any, any, any>, params, { dialect })
}
// A write without RETURNING sends back no rows, so it runs the way `execute`
// does: through `command`, which a ClickHouse client needs for a statement
// with no result set.
const run: DatabaseApi["run"] = (runnable, params) =>
Effect.flatMap(fillDefaults(runnable as Runnable), (filled) =>
Effect.flatMap(Effect.flatMap(compileFor(filled, params ?? {}), checkScope), (compiled) =>
compiled.kind !== "select" && compiled.returning === undefined
? Effect.as(execute(compiled), [])
: Effect.flatMap(rows(compiled), (wire) => compiled.decodeRows(wire)),
),
) as Effect.Effect<any, any, any>
// Whether the driver's insert id is this write's key. Postgres reports none.
// SQLite's and D1's last rowid is the connection's, not the statement's: an
// upsert that updated, or a WITHOUT ROWID table, leaves an earlier insert's,
// so it is not read for an `onConflictDoUpdate`.
const readsKey = (write: Runnable, kind: string): boolean =>
kind === "insert" &&
dialect.name !== "postgres" &&
!(dialect.functions === "sqlite" && "_state" in write && (write as AnyInsert)._state.conflict?.action === "update")
// The driver's own result of a write, which `unsafe(...).raw` returns: mysql2's
// ResultSetHeader, @effect/sql-pg's and PGlite's results, node:sqlite's
// `{ changes, lastInsertRowid }`, D1's result with its `meta`.
const runWrite: DatabaseApi["runWrite"] = (write, params) =>
Effect.flatMap(fillDefaults(write as Runnable), (filled) =>
Effect.flatMap(Effect.flatMap(compileFor(filled, params ?? {}), checkScope), (compiled) =>
dialect.name === "clickhouse"
? Effect.die(
new DatabaseError({
message: "ClickHouse reports no affected rows or generated keys; use run for a ClickHouse write",
sql: compiled.sql,
reason: "WriteResultUnsupported",
cause: undefined,
}),
)
: traceStatement(
dialect,
compiled,
guard(compiled).pipe(
Effect.andThen(driver(raw.unsafe(compiled.sql, compiled.parameters ?? []).raw)),
Effect.mapError(toDatabaseError(compiled.sql)),
Effect.flatMap((result) => writeResultOf(result, readsKey(filled, compiled.kind), compiled.sql)),
),
undefined,
traceOptions,
),
),
) as Effect.Effect<any, any, any>
// Effect's SQLite drivers (node:sqlite, D1, …) have no streaming read: their
// `.stream` dies with "executeStream not implemented". A SQLite-family
// dialect reads the whole result as `run` does and emits it row by row.
const cursorless = dialect.functions === "sqlite"
const wireStream = (statement: Statement & TracedStatement): Stream.Stream<Record<string, unknown>, DatabaseError> =>
cursorless
? Stream.fromIterableEffect(rows(statement))
: traceStream(
dialect,
statement,
Stream.unwrap(Effect.as(guard(statement), driverStream(raw.unsafe<Record<string, unknown>>(statement.sql, statement.parameters ?? []).stream))).pipe(
Stream.mapError(toDatabaseError(statement.sql)),
),
traceOptions,
)
// Each row through the query's row schema, as `decodeRows` does for a whole result.
const decodeStream = (
compiled: CompiledQuery<any, any>,
wire: Stream.Stream<Record<string, unknown>, DatabaseError>,
): Stream.Stream<unknown, DatabaseError | CompiledQueryDecodeError> => {
const schema = compiled.rowSchema
if (schema === undefined) return wire
const decode = Schema.decodeUnknownEffect(schema)
return wire.pipe(
Stream.zipWithIndex,
Stream.mapEffect(([row, rowIndex]) =>
decode(row).pipe(
Effect.mapError(
(cause) =>
decodeErrorFromCause({
prefix: `Compiled query row ${rowIndex} did not match its declared output schema`,
rowIndex,
cause,
dialect: dialect.name,
collection: compiled.collection,
}),
),
),
),
)
}
const stream: DatabaseApi["stream"] = (runnable, params) =>
Stream.unwrap(
Effect.flatMap(fillDefaults(runnable as Runnable), (filled) =>
Effect.map(Effect.flatMap(compileFor(filled, params ?? {}), checkScope), (compiled) =>
compiled.kind !== "select" && compiled.returning === undefined
? Stream.fromEffectDrain(execute(compiled))
: decodeStream(compiled, wireStream(compiled)),
),
),
) as Stream.Stream<any, any, any>
// D1's client sends a list of statements as one atomic request. It is read
// off the client, as D1 offers no transaction to run them in otherwise.
const nativeBatch = (sql as { readonly batch?: unknown }).batch
const batch: DatabaseApi["batch"] = (queries, params) => {
const list = queries as unknown as ReadonlyArray<Runnable>
const prepared = Effect.forEach(list, (runnable) =>
Effect.flatMap(fillDefaults(runnable), (filled) => Effect.flatMap(compileFor(filled, params ?? {}), checkScope)),
)
const decodeAll = (compiled: ReadonlyArray<CompiledQuery<any, any>>, wire: ReadonlyArray<ReadonlyArray<Record<string, unknown>>>) =>
Effect.forEach(compiled, (query, index) =>
query.kind !== "select" && query.returning === undefined ? Effect.succeed([]) : query.decodeRows(wire[index] ?? []),
)
const viaBatch = (compiled: ReadonlyArray<CompiledQuery<any, any>>) =>
Effect.gen(function* () {
for (const statement of compiled) yield* guard(statement)
const statements = compiled.map((statement) => raw.unsafe<Record<string, unknown>>(statement.sql, statement.parameters))
const wire = yield* traceBatch(
dialect,
compiled,
driver(
(nativeBatch as (statements: ReadonlyArray<unknown>) => Effect.Effect<ReadonlyArray<ReadonlyArray<Record<string, unknown>>>, unknown>).call(
sql,
statements,
),
).pipe(Effect.mapError(toDatabaseError(compiled.map((statement) => statement.sql).join(";\n")))),
traceOptions,
) as Effect.Effect<ReadonlyArray<ReadonlyArray<Record<string, unknown>>>, DatabaseError>
return yield* decodeAll(compiled, wire)
})
const inTransaction = (compiled: ReadonlyArray<CompiledQuery<any, any>>) =>
transaction(
Effect.forEach(compiled, (query) =>
query.kind !== "select" && query.returning === undefined
? Effect.as(execute(query), [])
: Effect.flatMap(rows(query), (wire) => query.decodeRows(wire)),
),
)
return Effect.flatMap(prepared, (compiled) =>
typeof nativeBatch === "function" && capabilities.support === "none" ? viaBatch(compiled) : inTransaction(compiled),
).pipe(
Effect.withSpan("effect_orm.batch", { attributes: { "db.operation.batch.size": list.length } }),
) as Effect.Effect<any, any, any>
}
const retryContention = <A, E, R>(effect: Effect.Effect<A, E, R>, retry?: RetryOptions) =>
Effect.flatMap(Effect.serviceOption(sql.transactionService), (open): Effect.Effect<A, E | TransactionOptionsRejected, R> =>
Option.isSome(open)
? Effect.fail(
new TransactionOptionsRejected({
message:
"retryContention inside an open transaction cannot retry: a serialization failure aborts the whole transaction. Retry the outermost transaction instead",
}),
)
: Effect.retry(effect, {
while: isContention,
times: retry?.times ?? 3,
schedule: retry?.schedule ?? Schedule.exponential("50 millis"),
}),
)
const once = <A, E, R>(
body: Effect.Effect<A, E, R>,
options: TransactionOptions,
): Effect.Effect<A, E | DatabaseError | TransactionError, Exclude<R, Transaction>> =>
Effect.gen(function* () {
if (capabilities.support === "none") {
return yield* new TransactionUnsupported({
dialect: dialect.name,
message: `${dialect.name} has no transactions; nothing was sent`,
})
}
const parent = yield* Effect.serviceOption(sql.transactionService)
const depth = Option.isSome(parent) ? parent.value[1] + 1 : 0
const settings = settingsOf(options)
if (depth > 0) {
if (hasSettings(settings) || options.retry !== undefined) {
return yield* new TransactionOptionsRejected({
message:
"a nested transaction cannot set isolationLevel, accessMode, deferrable or retry; they belong to the outermost transaction",
})
}
if (!capabilities.savepoints) {
return yield* new TransactionUnsupported({
dialect: dialect.name,
message: `${dialect.name} has no savepoints, so transactions cannot nest`,
})
}
} else {
if (settings.isolationLevel !== undefined && !capabilities.isolationLevels.includes(settings.isolationLevel)) {
return yield* new TransactionOptionsRejected({
message: `${dialect.name} does not support isolation level ${settings.isolationLevel}`,
})
}
if (settings.accessMode !== undefined && !capabilities.accessModes) {
return yield* new TransactionOptionsRejected({ message: `${dialect.name} does not support access modes` })
}
if (settings.deferrable !== undefined && !capabilities.deferrable) {
return yield* new TransactionOptionsRejected({ message: `${dialect.name} does not support deferrable transactions` })
}
}
const outer = yield* Effect.serviceOption(Transaction)
const info: TransactionInfo =
depth === 0 || Option.isNone(outer)
? { depth, isolationLevel: settings.isolationLevel, accessMode: settings.accessMode }
: { ...outer.value, depth }
// Settings travel in BEGIN when the dialect can write one, else as a
// `SET TRANSACTION` run first. Top level only: a savepoint takes no
// settings. Without settings the client keeps its own BEGIN (SQLite's
// `BEGIN IMMEDIATE`, for one).
const beginHook = capabilities.beginTransaction
const begin = depth === 0 && beginHook !== undefined ? beginHook(settings) : undefined
const setTransaction = depth === 0 && beginHook === undefined ? capabilities.setTransaction(settings) : undefined
const state: OpenState = { open: true, client: sql }
let bodyExit: Exit.Exit<unknown, unknown> | undefined
const inner = Effect.gen(function* () {
if (setTransaction !== undefined) yield* execute({ sql: setTransaction })
return yield* body
}).pipe(
// The reference applies to every top-level transaction started while it
// is provided; clear it for the body, so a transaction on another client
// keeps that client's BEGIN.
(effect) => (begin === undefined ? effect : Effect.provideService(effect, SqlClient.BeginTransaction, undefined)),
Effect.provideService(Transaction, info),
Effect.provideService(TransactionOpen, state),
Effect.onExit((exit) =>
Effect.sync(() => {
bodyExit = exit
}),
),
Effect.catchCause((cause): Effect.Effect<never, unknown> =>
Cause.hasDies(cause) && !Cause.hasInterrupts(cause) ? Effect.fail(new BodyDefect(cause)) : Effect.failCause(cause),
),
)
const transaction =
begin === undefined
? sql.withTransaction(inner)
: Effect.andThen(
observe({ sql: begin }),
sql.withTransaction(inner).pipe(Effect.provideService(SqlClient.BeginTransaction, begin)),
)
const exit = yield* Effect.exit(transaction.pipe(Effect.ensuring(committed(state))))
if (Exit.isSuccess(exit)) return exit.value
return yield* restoreCause<E>(exit.cause, bodyExit, depth, begin)
}).pipe(
Effect.withSpan("effect_orm.transaction", {
// Semconv defines no transaction attributes, and `db.*` is reserved for it.
attributes: {
...(options.isolationLevel !== undefined && { "effect_orm.transaction.isolation_level": options.isolationLevel }),
...(options.accessMode !== undefined && { "effect_orm.transaction.access_mode": options.accessMode }),
},
}),
) as Effect.Effect<A, E | DatabaseError | TransactionError, Exclude<R, Transaction>>
const transaction: DatabaseApi["transaction"] = (body, options = {}) =>
options.retry === undefined
? once(body, options)
: retryContention(once(body, options), options.retry === "contention" ? undefined : options.retry)
return { dialect, run, runWrite, batch, stream, query, execute, transaction, retryContention }
}
const field = (value: unknown, key: string): unknown =>
typeof value === "object" && value !== null && key in value ? (value as Record<string, unknown>)[key] : undefined
// A count or key as a driver sends it: a number, a bigint (node:sqlite), or a
// string past 2^53 (mysql2 with `supportBigNumbers`). Past 2^53 it is not
// exact as a number, so it fails rather than being rounded.
const integerOf = (value: unknown, what: string, sql: string): Effect.Effect<number | undefined, DatabaseError> => {
if (value === undefined || value === null) return Effect.succeed(undefined)
const n = typeof value === "number" ? value : typeof value === "bigint" || typeof value === "string" ? Number(value) : Number.NaN
return Number.isSafeInteger(n) && String(value) === String(n)
? Effect.succeed(n)
: Effect.fail(
new DatabaseError({
message: `the driver reported ${what} ${String(value)}, which is not a safe JavaScript integer`,
sql,
reason: "UnsafeInteger",
cause: undefined,
}),
)
}
/** @internal — what a driver's raw write result says, whichever driver sent it. */
export const writeResultOf = (result: unknown, readKey: boolean, sql: string): Effect.Effect<WriteResult, DatabaseError> =>
Effect.gen(function* () {
const meta = field(result, "meta")
const affected = field(result, "affectedRows") ?? field(result, "rowCount") ?? field(result, "changes") ?? field(meta, "changes")
const affectedRows = yield* integerOf(affected, "affected rows", sql)
// The write has already run, and outside a transaction it is committed, so this
// is an error in the channel, not a defect that would read as "nothing happened".
if (affectedRows === undefined) {
return yield* new DatabaseError({
message:
"the write ran, but the SQL client returned no affected-row count; runWrite reads @effect/sql-mysql2, @effect/sql-pg, PGlite, node:sqlite and D1 results",
sql,
reason: "WriteResultUnsupported",
cause: undefined,
})
}
// node:sqlite's and D1's last rowid outlives the insert that set it, so it is
// read only for an insert that wrote a row. mysql2 reports 0 for no key; 0 is
// a valid SQLite rowid, so only mysql2's 0 means none.
if (!readKey || affectedRows === 0) return { affectedRows, insertId: undefined }
const mysqlKey = yield* integerOf(field(result, "insertId"), "insert id", sql)
if (mysqlKey !== undefined) return { affectedRows, insertId: mysqlKey === 0 ? undefined : mysqlKey }
const insertId = yield* integerOf(field(result, "lastInsertRowid") ?? field(meta, "last_row_id"), "insert id", sql)
return { affectedRows, insertId }
})
/**
* Turn what came out of `withTransaction` back into what the caller should see.
* Effect fails with the `SqlError` of a failed COMMIT (or dies, when cleanup
* after it failed too), and dies on a failed ROLLBACK, which replaces the body's
* own exit. Body defects were carried through as `BodyDefect`, so any other
* defect that is a `SqlError` came from transaction control. `begin` is the
* statement that started the transaction, when it was not the client's BEGIN.
*/
const restoreCause = <E>(
cause: Cause.Cause<unknown>,
bodyExit: Exit.Exit<unknown, unknown> | undefined,
depth: number,
begin: string | undefined,
): Effect.Effect<never, E | DatabaseError | TransactionCommitFailed | TransactionRollbackFailed> => {
const failure = Cause.findError(cause)
if (failure._tag === "Success" && failure.success instanceof BodyDefect) {
return Effect.failCause(failure.success.cause as Cause.Cause<E>)
}
const defect = Cause.findDefect(cause)
// The body succeeded, so a `SqlError` here came from COMMIT or RELEASE.
if (bodyExit !== undefined && Exit.isSuccess(bodyExit)) {
const error =
failure._tag === "Success" && isSqlError(failure.success)
? failure.success
: defect._tag === "Success" && isSqlError(defect.success)
? defect.success
: undefined
if (error === undefined) return Effect.failCause(cause as Cause.Cause<E>)
const sqlState = sqlStateOf(error)
const errorCode = errorCodeOf(error)
return Effect.fail(
new TransactionCommitFailed({
message: `${depth === 0 ? "COMMIT" : "releasing the savepoint"} failed: ${firstLine(error)}`,
reason: reasonOf(error),
...(sqlState === undefined ? undefined : { sqlState }),
...(errorCode === undefined ? undefined : { errorCode }),
cause: error,
}),
)
}
if (defect._tag === "Success" && isSqlError(defect.success)) {
const error = defect.success
// The body never ran: BEGIN or SAVEPOINT died, not ROLLBACK.
if (bodyExit === undefined) return Effect.fail(toDatabaseError(depth === 0 ? (begin ?? "BEGIN") : "SAVEPOINT")(error))
// An interrupted transaction whose ROLLBACK died stays interrupted.
if (Cause.hasInterrupts(bodyExit.cause)) return Effect.failCause(bodyExit.cause as Cause.Cause<E>)
return Effect.fail(
new TransactionRollbackFailed({
message: `ROLLBACK failed after the transaction body failed: ${firstLine(error)}`,
bodyCause: bodyExit.cause,
cause: error,
}),
)
}
// BEGIN or SAVEPOINT failed before the body ran.
if (bodyExit === undefined && failure._tag === "Success" && isSqlError(failure.success)) {
return Effect.fail(toDatabaseError(depth === 0 ? (begin ?? "BEGIN") : "SAVEPOINT")(failure.success))
}
return Effect.failCause(cause as Cause.Cause<E>)
}
/** A `Database` layer over the `SqlClient` in context. */
export const layerSqlClient = (options: FromSqlClientOptions): Layer.Layer<Database, never, SqlClient.SqlClient> =>
Layer.effect(
Database,
Effect.gen(function* () {
return fromSqlClient<string>(yield* SqlClient.SqlClient, options)
}),
)
/** `run` on the `Database` in context. */
export const run = <Q extends Runnable, const Given extends object = {}>(
query: Q &
RunCheck<Q> &
ParamsSatisfied<QueryParams<Q>, Given> &
DialectSatisfied<QueryParams<Q>, string> &
SourcesSatisfied<QueryParams<Q>>,
params?: Given,
): Effect.Effect<
ReadonlyArray<RowOf<Q>>,
DatabaseError | QueryBuilderError | CompiledQueryDecodeError,
Database | RequirementsOf<Q>
> => Effect.flatMap(Effect.service(Database), (db) => db.run(query, params))
/** `batch` on the `Database` in context. */
export const batch = <const Qs extends ReadonlyArray<Runnable>, const Given extends object = {}>(
queries: Qs & BatchCheck<Qs, Given, string>,
params?: Given,
): Effect.Effect<
BatchRows<Qs>,
DatabaseError | QueryBuilderError | CompiledQueryDecodeError | TransactionError,
Database | RequirementsOf<Qs[number]>
> => Effect.flatMap(Effect.service(Database), (db) => db.batch(queries as never, params))
/** What `run` can fail with. */
type RunError = DatabaseError | QueryBuilderError | CompiledQueryDecodeError
const cardinalityError = (expected: ResultCardinalityError["expected"], rows: number) =>
new ResultCardinalityError({
message: `expected ${expected === "one" ? "exactly one row" : expected === "atMostOne" ? "at most one row" : "at least one row"}, got ${rows}`,
expected,
rows,
})
/**
* `run`, for a query that must return exactly one row. Zero rows or more than
* one fail with `ResultCardinalityError`. No `LIMIT` is added, so a duplicate
* is found, not hidden.
*/
export const runOne = <Q extends Runnable, const Given extends object = {}>(
query: Q &
RunCheck<Q> &
ParamsSatisfied<QueryParams<Q>, Given> &
DialectSatisfied<QueryParams<Q>, string> &
SourcesSatisfied<QueryParams<Q>>,
params?: Given,
): Effect.Effect<RowOf<Q>, RunError | ResultCardinalityError, Database | RequirementsOf<Q>> =>
Effect.flatMap(run(query, params), (rows) =>
Arr.isReadonlyArrayNonEmpty(rows) && rows.length === 1 ? Effect.succeed(rows[0]) : Effect.fail(cardinalityError("one", rows.length)),
)
/**
* `run`, for a query that returns at most one row: `Option.none()` for zero
* rows, `Option.some(row)` for one. More than one fails with
* `ResultCardinalityError`. No `LIMIT` is added.
*/
export const runOption = <Q extends Runnable, const Given extends object = {}>(
query: Q &
RunCheck<Q> &
ParamsSatisfied<QueryParams<Q>, Given> &
DialectSatisfied<QueryParams<Q>, string> &
SourcesSatisfied<QueryParams<Q>>,
params?: Given,
): Effect.Effect<Option.Option<RowOf<Q>>, RunError | ResultCardinalityError, Database | RequirementsOf<Q>> =>
Effect.flatMap(run(query, params), (rows) =>
rows.length > 1 ? Effect.fail(cardinalityError("atMostOne", rows.length)) : Effect.succeed(Arr.head(rows)),
)
/**
* `run`, for a query that must return at least one row. Zero rows fail with
* `ResultCardinalityError`; otherwise every row comes back, typed as a
* non-empty array.
*/
export const runNonEmpty = <Q extends Runnable, const Given extends object = {}>(
query: Q &
RunCheck<Q> &
ParamsSatisfied<QueryParams<Q>, Given> &
DialectSatisfied<QueryParams<Q>, string> &
SourcesSatisfied<QueryParams<Q>>,
params?: Given,
): Effect.Effect<Arr.NonEmptyReadonlyArray<RowOf<Q>>, RunError | ResultCardinalityError, Database | RequirementsOf<Q>> =>
Effect.flatMap(run(query, params), (rows) =>
Arr.isReadonlyArrayNonEmpty(rows) ? Effect.succeed(rows) : Effect.fail(cardinalityError("nonEmpty", 0)),
)
/** `runWrite` on the `Database` in context. */
export const runWrite = <Q extends Write, const Given extends object = {}>(
query: Q &
ParamsSatisfied<QueryParams<Q>, Given> &
DialectSatisfied<QueryParams<Q>, string> &
SourcesSatisfied<QueryParams<Q>>,
params?: Given,
): Effect.Effect<WriteResult, DatabaseError | QueryBuilderError, Database | RequirementsOf<Q>> =>
Effect.flatMap(Effect.service(Database), (db) => db.runWrite(query, params))
/** `stream` on the `Database` in context. */
export const stream = <Q extends Runnable, const Given extends object = {}>(
query: Q &
RunCheck<Q> &
ParamsSatisfied<QueryParams<Q>, Given> &
DialectSatisfied<QueryParams<Q>, string> &
SourcesSatisfied<QueryParams<Q>>,
params?: Given,
): Stream.Stream<RowOf<Q>, DatabaseError | QueryBuilderError | CompiledQueryDecodeError, Database | RequirementsOf<Q>> =>
Stream.unwrap(Effect.map(Effect.service(Database), (db) => db.stream(query, params)))
/** `query` on the `Database` in context. */
export const query: {
(statement: StatementInput): Effect.Effect<ReadonlyArray<Record<string, unknown>>, DatabaseError, Database>
<A>(
statement: StatementInput,
schema: RowSchema<A>,
): Effect.Effect<ReadonlyArray<A>, DatabaseError | CompiledQueryDecodeError, Database>
} = ((statement: StatementInput, schema?: RowSchema<unknown>) =>
Effect.flatMap(
Effect.service(Database),
(db): Effect.Effect<ReadonlyArray<unknown>, DatabaseError | CompiledQueryDecodeError> =>
schema === undefined ? db.query(statement) : db.query(statement, schema),
)) as typeof query
/** `execute` on the `Database` in context. */
export const execute = (statement: StatementInput): Effect.Effect<void, DatabaseError, Database> =>
Effect.flatMap(Effect.service(Database), (db) => db.execute(statement))
/**
* Mark an effect as correct only inside a transaction. It adds `Transaction`
* to the requirements, so it does not compile until `transaction` wraps it, as
* an `Effect.fn` pipe argument or with `.pipe`:
*
* ```ts
* const revokeFamily = Effect.fn("revokeFamily")(function* (family: string) { ... }, Db.requireTransaction)
* ```
*/
export const requireTransaction = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R | Transaction> =>
Effect.andThen(Effect.service(Transaction), self)
/**
* Queue `effect` to run after the outermost transaction commits, and never if