Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Client.integration.test.ts

858 lines31.3 KB

1import { PgClient } from "@effect/sql-pg"
2import { assert, expect, it } from "@effect/vitest"
3import {
4 Cause,
5 Context,
6 DateTime,
7 Deferred,
8 Effect,
9 Fiber,
10 Layer,
11 Option,
12 Queue,
13 Redacted,
14 Schedule,
15 Schema,
16 Stream,
17 String
18} from "effect"
19import * as Reactivity from "effect/reactivity/Reactivity"
20import { Model } from "effect/schema"
21import { SqlClient, SqlError, SqlModel } from "effect/sql"
22import * as Statement from "effect/sql/Statement"
23import { TestClock } from "effect/testing"
24import { PgContainer } from "./utils.ts"
25​
26const compilerTransform = PgClient.makeCompiler(String.camelToSnake)
27const transformsNested = Statement.defaultTransforms(String.snakeToCamel)
28const transforms = Statement.defaultTransforms(String.snakeToCamel, false)
29​
30it.layer(PgContainer.layerClient, { timeout: "30 seconds" })("PgClient", (it) => {
31 it.effect("round trips Model.DateTimeInsertFromDate through a repository", () =>
32 Effect.gen(function*() {
33 class Entry extends Model.Class<Entry>("Entry")({
34 id: Schema.Int.pipe(Model.FieldExcept(["insert"])),
35 created_at: Model.DateTimeInsertFromDate
36 }) {}
37​
38 const sql = yield* PgClient.PgClient
39 const repo = yield* SqlModel.makeRepository(Entry, {
40 tableName: "model_timestamp",
41 idColumn: "id",
42 spanPrefix: "EntryRepository"
43 })
44 const instant = new Date("2024-05-06T07:08:09.123Z")
45 yield* sql.withTransaction(Effect.gen(function*() {
46 yield* sql`SET LOCAL TIME ZONE 'Europe/Berlin'`
47 yield* sql`CREATE TEMP TABLE model_timestamp (id SERIAL PRIMARY KEY, created_at TIMESTAMPTZ) ON COMMIT DROP`
48 const inserted = yield* repo.insert(
49 Entry.insert.make({ created_at: Model.Override(DateTime.makeUnsafe(instant)) })
50 )
51 assert.strictEqual(DateTime.toEpochMillis(inserted.created_at), instant.getTime())
52 const selected = yield* repo.findById(inserted.id)
53 assert.deepStrictEqual(selected, inserted)
54 assert.strictEqual(DateTime.toEpochMillis(selected.created_at), instant.getTime())
55 }))
56 }))
57​
58 it.effect("insert helper", () =>
59 Effect.gen(function*() {
60 const sql = yield* PgClient.PgClient
61 const [query, params] = sql`INSERT INTO people ${sql.insert({ name: "Tim", age: 10 })}`.compile()
62 expect(query).toEqual(`INSERT INTO people ("name","age") VALUES ($1,$2)`)
63 expect(params).toEqual(["Tim", 10])
64 }))
65​
66 it.effect("updateValues helper", () =>
67 Effect.gen(function*() {
68 const sql = yield* PgClient.PgClient
69 const [query, params] = sql`UPDATE people SET name = data.name FROM ${
70 sql.updateValues(
71 [{ name: "Tim" }, { name: "John" }],
72 "data"
73 )
74 }`.compile()
75 expect(query).toEqual(
76 `UPDATE people SET name = data.name FROM (values ($1),($2)) AS "data"("name")`
77 )
78 expect(params).toEqual(["Tim", "John"])
79 }))
80​
81 it.effect("updateValues helper returning", () =>
82 Effect.gen(function*() {
83 const sql = yield* PgClient.PgClient
84 const [query, params] = sql`UPDATE people SET name = data.name FROM ${
85 sql.updateValues(
86 [{ name: "Tim" }, { name: "John" }],
87 "data"
88 ).returning("*")
89 }`.compile()
90 expect(query).toEqual(
91 `UPDATE people SET name = data.name FROM (values ($1),($2)) AS "data"("name") RETURNING *`
92 )
93 expect(params).toEqual(["Tim", "John"])
94 }))
95​
96 it.effect("update helper", () =>
97 Effect.gen(function*() {
98 const sql = yield* PgClient.PgClient
99 let result = sql`UPDATE people SET ${sql.update({ name: "Tim" })}`.compile()
100 expect(result[0]).toEqual(`UPDATE people SET "name" = $1`)
101 expect(result[1]).toEqual(["Tim"])
102​
103 result = sql`UPDATE people SET ${sql.update({ name: "Tim", age: 10 }, ["age"])}`.compile()
104 expect(result[0]).toEqual(`UPDATE people SET "name" = $1`)
105 expect(result[1]).toEqual(["Tim"])
106 }))
107​
108 it.effect("update helper returning", () =>
109 Effect.gen(function*() {
110 const sql = yield* PgClient.PgClient
111 const result = sql`UPDATE people SET ${sql.update({ name: "Tim" }).returning("*")}`.compile()
112 expect(result[0]).toEqual(`UPDATE people SET "name" = $1 RETURNING *`)
113 expect(result[1]).toEqual(["Tim"])
114 }))
115​
116 it.effect("binds an empty array using the type inferred by PostgreSQL", () =>
117 Effect.gen(function*() {
118 const sql = yield* SqlClient.SqlClient
119 const ids: ReadonlyArray<string> = []
120 const rows = yield* sql`SELECT 1 WHERE 'a' = ANY(${ids})`
121 assert.deepStrictEqual(rows, [])
122 }))
123​
124 it.effect("array helper", () =>
125 Effect.gen(function*() {
126 const sql = yield* PgClient.PgClient
127 const [query, params] = sql`SELECT * FROM ${sql("people")} WHERE id IN ${sql.in([1, 2, "string"])}`.compile()
128 expect(query).toEqual(`SELECT * FROM "people" WHERE id IN ($1,$2,$3)`)
129 expect(params).toEqual([1, 2, "string"])
130 }))
131​
132 it.effect("array helper with column", () =>
133 Effect.gen(function*() {
134 const sql = yield* PgClient.PgClient
135 let result = sql`SELECT * FROM ${sql("people")} WHERE ${sql.in("id", [1, 2, "string"])}`.compile()
136 expect(result[0]).toEqual(`SELECT * FROM "people" WHERE "id" IN ($1,$2,$3)`)
137 expect(result[1]).toEqual([1, 2, "string"])
138​
139 result = sql`SELECT * FROM ${sql("people")} WHERE ${sql.in("id", [])}`.compile()
140 expect(result[0]).toEqual(`SELECT * FROM "people" WHERE 1=0`)
141 expect(result[1]).toEqual([])
142 }))
143​
144 it.effect("and", () =>
145 Effect.gen(function*() {
146 const sql = yield* PgClient.PgClient
147 const now = new Date()
148 const result = sql`SELECT * FROM ${sql("people")} WHERE ${
149 sql.and([
150 sql.in("name", ["Tim", "John"]),
151 sql`created_at < ${now}`
152 ])
153 }`.compile()
154 expect(result[0]).toEqual(`SELECT * FROM "people" WHERE ("name" IN ($1,$2) AND created_at < $3)`)
155 expect(result[1]).toEqual(["Tim", "John", now])
156 }))
157​
158 it("transform nested", () => {
159 assert.deepEqual(
160 transformsNested.array([
161 {
162 a_key: 1,
163 nested: [{ b_key: 2 }],
164 arr_primitive: [1, "2", true]
165 }
166 ]) as any,
167 [
168 {
169 aKey: 1,
170 nested: [{ bKey: 2 }],
171 arrPrimitive: [1, "2", true]
172 }
173 ]
174 )
175 })
176​
177 it("transform non nested", () => {
178 assert.deepEqual(
179 transforms.array([
180 {
181 a_key: 1,
182 nested: [{ b_key: 2 }],
183 arr_primitive: [1, "2", true]
184 }
185 ]) as any,
186 [
187 {
188 aKey: 1,
189 nested: [{ b_key: 2 }],
190 arrPrimitive: [1, "2", true]
191 }
192 ]
193 )
194​
195 assert.deepEqual(
196 transforms.array([
197 {
198 json_field: {
199 test_value: [1, true, null, "text"],
200 test_nested: {
201 test_value: [1, true, null, "text"]
202 }
203 }
204 }
205 ]) as any,
206 [
207 {
208 jsonField: {
209 test_value: [1, true, null, "text"],
210 test_nested: {
211 test_value: [1, true, null, "text"]
212 }
213 }
214 }
215 ]
216 )
217 })
218​
219 it.effect("insert fragments", () =>
220 Effect.gen(function*() {
221 const sql = yield* PgClient.PgClient
222 const [query, params] = sql`INSERT INTO people ${
223 sql.insert({
224 name: "Tim",
225 age: 10,
226 json: sql.json({ a: 1 })
227 })
228 }`.compile()
229 assert.strictEqual(
230 query,
231 "INSERT INTO people (\"name\",\"age\",\"json\") VALUES ($1,$2,$3)"
232 )
233 assert.lengthOf(params, 3)
234 }))
235​
236 it.effect("update fragments", () =>
237 Effect.gen(function*() {
238 const sql = yield* PgClient.PgClient
239 const now = new Date()
240 const [query, params] = sql`UPDATE people SET json = data.json FROM ${
241 sql.updateValues(
242 [{ json: sql.json({ a: 1 }) }, { json: sql.json({ b: 1 }) }],
243 "data"
244 )
245 } WHERE created_at > ${now}`.compile()
246 assert.strictEqual(
247 query,
248 `UPDATE people SET json = data.json FROM (values ($1),($2)) AS "data"("json") WHERE created_at > $3`
249 )
250 assert.lengthOf(params, 3)
251 }))
252​
253 it.effect("onDialect", () =>
254 Effect.gen(function*() {
255 const sql = yield* PgClient.PgClient
256 assert.strictEqual(
257 sql.onDialect({
258 sqlite: () => "A",
259 pg: () => "B",
260 mysql: () => "C",
261 mssql: () => "D",
262 clickhouse: () => "E"
263 }),
264 "B"
265 )
266 assert.strictEqual(
267 sql.onDialectOrElse({
268 orElse: () => "A",
269 pg: () => "B"
270 }),
271 "B"
272 )
273 }))
274​
275 it.effect("identifier transform", () =>
276 Effect.gen(function*() {
277 const sql = yield* PgClient.PgClient
278 const [query] = compilerTransform.compile(
279 sql`SELECT * from ${sql("peopleTest")}`,
280 false
281 )
282 expect(query).toEqual(`SELECT * from "people_test"`)
283 }))
284​
285 it.effect("jsonb", () =>
286 Effect.gen(function*() {
287 const sql = yield* PgClient.PgClient
288 const rows = yield* sql<{ json: unknown }>`select ${sql.json({ testValue: 123 })}::jsonb as json`
289 expect(rows[0].json).toEqual({ testValue: 123 })
290 }))
291​
292 it.effect("reads scalar enums as strings without registering their OIDs", () =>
293 Effect.gen(function*() {
294 const sql = yield* PgClient.PgClient
295 yield* sql.withTransaction(Effect.gen(function*() {
296 yield* sql`CREATE TYPE capability_scalar AS ENUM ('use_key', 'manage', 'gérer')`
297 const rows = yield* sql`
298 SELECT 'use_key'::capability_scalar AS capability,
299 ${"gérer"}::capability_scalar AS bound,
300 NULL::capability_scalar AS nullable
301 `
302 yield* sql`DROP TYPE capability_scalar`
303 assert.deepStrictEqual(rows, [{ capability: "use_key", bound: "gérer", nullable: null }])
304 }))
305 }))
306​
307 it.effect("reads anonymous records and record arrays", () =>
308 Effect.gen(function*() {
309 const sql = yield* PgClient.PgClient
310 const rows = yield* sql`
311 SELECT ROW(1, 'a', NULL::int4, ROW(true, ARRAY[1, 2])) AS record,
312 ARRAY[ROW(1, 'a'), ROW(2, 'b')] AS records
313 `
314 assert.deepStrictEqual(rows, [{ record: [1, "a", null, [true, [1, 2]]], records: [[1, "a"], [2, "b"]] }])
315 }))
316​
317 it.effect("reads bytea as Uint8Array", () =>
318 Effect.gen(function*() {
319 const sql = yield* PgClient.PgClient
320 const payload = new Uint8Array([0, 1, 254, 255])
321 const rows = yield* sql`SELECT ${payload}::bytea AS payload`
322 assert.instanceOf(rows[0].payload, Uint8Array)
323 assert.deepStrictEqual(rows, [{ payload }])
324 }))
325​
326 it.effect("stream", () =>
327 Effect.gen(function*() {
328 const sql = yield* SqlClient.SqlClient
329 const rows = yield* sql`SELECT generate_series(1, 3)`.stream.pipe(
330 Stream.runCollect
331 )
332 expect(rows).toEqual([
333 { "generate_series": 1 },
334 { "generate_series": 2 },
335 { "generate_series": 3 }
336 ])
337 }))
338​
339 it.effect("releases completed nested transaction locks", () =>
340 Effect.gen(function*() {
341 const sql = yield* PgClient.PgClient
342 const locks = sql`SELECT count(*)::integer AS count FROM pg_locks
343 WHERE pid = pg_backend_pid() AND locktype = 'transactionid'`
344 yield* sql.withTransaction(Effect.gen(function*() {
345 yield* sql`CREATE TEMP TABLE savepoint_locks (value INTEGER) ON COMMIT DROP`
346​
347 yield* sql.withTransaction(sql`INSERT INTO savepoint_locks VALUES (1)`)
348 assert.deepStrictEqual(yield* locks, [{ count: 1 }])
349​
350 const error = yield* sql.withTransaction(
351 sql`INSERT INTO savepoint_locks VALUES (2)`.pipe(Effect.andThen(Effect.fail("rollback")))
352 ).pipe(Effect.flip)
353 assert.strictEqual(error, "rollback")
354 assert.deepStrictEqual(yield* locks, [{ count: 1 }])
355​
356 assert.deepStrictEqual(yield* sql`SELECT value FROM savepoint_locks`, [{ value: 1 }])
357 }))
358 }))
359​
360 it.effect("preserves successful concurrent nested transactions", () =>
361 Effect.gen(function*() {
362 const sql = yield* PgClient.PgClient
363 const firstStarted = yield* Deferred.make<void>()
364 const firstInserted = yield* Deferred.make<void>()
365​
366 const rows = yield* sql.withTransaction(
367 Effect.gen(function*() {
368 yield* sql`CREATE TEMP TABLE nested_transactions (value TEXT) ON COMMIT DROP`
369 yield* Effect.all([
370 sql.withTransaction(
371 Effect.gen(function*() {
372 yield* Deferred.succeed(firstStarted, undefined)
373 yield* Effect.sleep("100 millis")
374 yield* sql`INSERT INTO nested_transactions VALUES ('first')`
375 yield* Deferred.succeed(firstInserted, undefined)
376 })
377 ),
378 Deferred.await(firstStarted).pipe(
379 Effect.andThen(sql.withTransaction(
380 Deferred.await(firstInserted).pipe(
381 Effect.andThen(Effect.fail("rollback"))
382 )
383 ))
384 )
385 ], { concurrency: "unbounded" }).pipe(Effect.catch(() => Effect.void))
386 return yield* sql<{ value: string }>`SELECT value FROM nested_transactions`
387 })
388 )
389​
390 assert.deepStrictEqual(rows, [{ value: "first" }])
391 }).pipe(TestClock.withLive))
392​
393 it.effect("fails a transaction whose COMMIT rolls back after a caught error", () =>
394 Effect.gen(function*() {
395 const sql = yield* PgClient.PgClient
396 const cause = yield* sql.withTransaction(Effect.gen(function*() {
397 yield* Effect.ignore(sql`SELECT 1 / 0`)
398 })).pipe(Effect.sandbox, Effect.flip)
399​
400 assert.isFalse(Cause.hasDies(cause))
401 assert.isTrue(Cause.hasFails(cause))
402 const error = Cause.squash(cause)
403 assert.instanceOf(error, SqlError.SqlError)
404 assert.strictEqual(error.reason._tag, "UnknownError")
405 assert.strictEqual(error.reason.operation, "commit")
406 }))
407​
408 it.effect("keeps the typed error when the server ends the session in a nested transaction", () =>
409 Effect.gen(function*() {
410 const sql = yield* PgClient.PgClient
411 const cause = yield* sql.withTransaction(
412 sql.withTransaction(sql`SELECT pg_terminate_backend(pg_backend_pid())`)
413 ).pipe(Effect.sandbox, Effect.flip)
414​
415 assert.isFalse(Cause.hasDies(cause))
416 assert.instanceOf(Cause.squash(cause), SqlError.SqlError)
417 }))
418​
419 it.effect("afterCommit runs once other connections see the transaction's rows", () =>
420 Effect.gen(function*() {
421 const sql = yield* PgClient.PgClient
422 yield* sql`CREATE TABLE after_commit_visibility (value INTEGER)`
423 let seen: ReadonlyArray<{ readonly count: number }> = []
424​
425 yield* sql.withTransaction(Effect.gen(function*() {
426 yield* sql`INSERT INTO after_commit_visibility VALUES (1)`
427 yield* sql.afterCommit(
428 sql<{ count: number }>`SELECT count(*)::integer AS count FROM after_commit_visibility`.pipe(
429 Effect.map((rows) => {
430 seen = rows
431 }),
432 Effect.orDie
433 )
434 )
435 }))
436​
437 assert.deepStrictEqual(seen, [{ count: 1 }])
438 }))
439})
440​
441it.layer(PgContainer.layerMakeClientUnprepared, { timeout: "30 seconds" })(
442 "PgClient.makeClient without preparation",
443 (it) => {
444 it.effect("fails an aborted COMMIT and reuses the connection", () =>
445 Effect.gen(function*() {
446 const sql = yield* PgClient.PgClient
447 const cause = yield* sql.withTransaction(Effect.gen(function*() {
448 yield* Effect.ignore(sql`SELECT 1 / 0`)
449 })).pipe(Effect.sandbox, Effect.flip)
450​
451 assert.isFalse(Cause.hasDies(cause))
452 assert.isTrue(Cause.hasFails(cause))
453 const error = Cause.squash(cause)
454 assert.instanceOf(error, SqlError.SqlError)
455 assert.strictEqual(error.reason._tag, "UnknownError")
456 assert.strictEqual(error.reason.operation, "commit")
457​
458 const rows = yield* sql.withTransaction(sql<{ value: number }>`SELECT 1 AS value`)
459 assert.deepStrictEqual(rows, [{ value: 1 }])
460 }))
461 }
463​
464it.layer(PgContainer.layerMakeClient, { timeout: "30 seconds" })("PgClient.makeClient", (it) => {
465 it.effect("connects before executing queries", () =>
466 Effect.gen(function*() {
467 const sql = yield* PgClient.PgClient
468 const rows = yield* sql<{ value: number }>`SELECT 1 AS value`
469 assert.deepStrictEqual(rows, [{ value: 1 }])
470 }))
471​
472 it.effect("skips prepared statements for unprepared executions only", () =>
473 Effect.gen(function*() {
474 const sql = yield* PgClient.PgClient
475 const rows = sql<{ unprepared_row: number }>`SELECT ${1}::int4 AS unprepared_row`
476 const values = sql`SELECT ${2}::int4 AS unprepared_values`
477 const preparedStatements = sql<{ statement: string }>`
478 SELECT statement FROM pg_prepared_statements
479 WHERE statement IN (
480 'SELECT $1::int4 AS unprepared_row',
481 'SELECT $1::int4 AS unprepared_values'
482 )
483 ORDER BY statement
484 `
485​
486 assert.deepStrictEqual(yield* rows.unprepared, [{ unprepared_row: 1 }])
487 assert.deepStrictEqual(yield* values.valuesUnprepared, [[2]])
488 assert.deepStrictEqual(yield* preparedStatements, [])
489​
490 assert.deepStrictEqual(yield* rows, [{ unprepared_row: 1 }])
491 assert.deepStrictEqual(yield* values.values, [[2]])
492 assert.deepStrictEqual(yield* preparedStatements, [
493 { statement: "SELECT $1::int4 AS unprepared_row" },
494 { statement: "SELECT $1::int4 AS unprepared_values" }
495 ])
496 }))
497​
498 it.effect("pins the primary connection for streams by default", () =>
499 Effect.gen(function*() {
500 const sql = yield* PgClient.PgClient
501 const streamStarted = yield* Deferred.make<void>()
502 const releaseStream = yield* Deferred.make<void>()
503 const streamFiber = yield* sql<{ value: number }>`SELECT generate_series(1, 2) AS value`.stream.pipe(
504 Stream.tap(() =>
505 Effect.andThen(
506 Deferred.succeed(streamStarted, undefined),
507 Deferred.await(releaseStream)
508 )
509 ),
510 Stream.runCollect,
511 Effect.forkScoped
512 )
513​
514 yield* Deferred.await(streamStarted)
515 const rows = yield* sql<{ value: number }>`SELECT 1 AS value`.pipe(
516 Effect.timeoutOption("100 millis")
517 )
518 yield* Deferred.succeed(releaseStream, undefined)
519 yield* Fiber.join(streamFiber)
520​
521 assert.isTrue(Option.isNone(rows))
522 }).pipe(TestClock.withLive))
523​
524 it.effect("times out a queued stream before the transaction connection is released", () =>
525 Effect.gen(function*() {
526 const sql = yield* PgClient.PgClient
527 yield* sql.withTransaction(Effect.gen(function*() {
528 const started = yield* Deferred.make<void>()
529 const release = yield* Deferred.make<void>()
530 const holder = yield* sql`SELECT 1`.stream.pipe(
531 Stream.runForEach(() => Effect.andThen(Deferred.succeed(started, undefined), Deferred.await(release))),
532 Effect.forkChild
533 )
534 yield* Deferred.await(started)
535 const queued = yield* sql`SELECT 2`.stream.pipe(Stream.runDrain, Effect.timeoutOption(10), Effect.forkChild)
536 yield* TestClock.adjust(10)
537 const completedWhileQueued = queued.pollUnsafe() !== undefined
538 yield* Deferred.succeed(release, undefined)
539 yield* Fiber.join(holder)
540 assert.isTrue(Option.isNone(yield* Fiber.join(queued)))
541 assert.isTrue(completedWhileQueued, "stream timeout waited for the connection")
542 assert.deepStrictEqual(yield* sql`SELECT 3 AS value`, [{ value: 3 }])
543 }))
544 }))
545​
546 it.effect("serializes transactions on its single connection", () =>
547 Effect.gen(function*() {
548 const sql = yield* PgClient.PgClient
549 const firstBodyStarted = yield* Deferred.make<void>()
550 const releaseFirstBody = yield* Deferred.make<void>()
551 const secondBodyStarted = yield* Deferred.make<void>()
552​
553 const first = yield* sql.withTransaction(Effect.gen(function*() {
554 yield* Deferred.succeed(firstBodyStarted, undefined)
555 yield* Deferred.await(releaseFirstBody)
556 })).pipe(Effect.forkScoped)
557 yield* Deferred.await(firstBodyStarted)
558 const second = yield* sql.withTransaction(
559 Deferred.succeed(secondBodyStarted, undefined)
560 ).pipe(Effect.forkScoped)
561​
562 const overlap = yield* Deferred.await(secondBodyStarted).pipe(
563 Effect.timeoutOption("100 millis"),
564 TestClock.withLive
565 )
566 yield* Deferred.succeed(releaseFirstBody, undefined)
567 yield* Fiber.join(first)
568 yield* Fiber.join(second)
569​
570 assert.isTrue(Option.isNone(overlap))
571 }))
572​
573 // A transaction pooler moves the session to another server between
574 // transactions, where the statements prepared on the last one do not exist.
575 it.effect("ends transactions whose prepared statements went missing", () =>
576 Effect.gen(function*() {
577 // Its own session, so `DEALLOCATE ALL` cannot affect concurrent tests.
578 const sql = yield* PgClient.makeClient((yield* PgClient.PgClient).config)
579 const select = sql<{ value: number }>`SELECT ${1}::int4 AS value`
580 const assertSqlFailure = (cause: Cause.Cause<unknown>) => {
581 assert.isFalse(Cause.hasDies(cause))
582 const error = Cause.squash(cause)
583 assert.instanceOf(error, SqlError.SqlError)
584 assert.propertyVal(error.reason.cause, "code", "26000")
585 }
586 // Prepares BEGIN, the body, ROLLBACK and COMMIT.
587 yield* sql.withTransaction(Effect.andThen(select, Effect.fail("rollback"))).pipe(Effect.flip)
588 yield* sql.withTransaction(select)
589 yield* sql`DEALLOCATE ALL`.unprepared
590​
591 // The body fails on its lost statement, and ROLLBACK still has to run.
592 assertSqlFailure(yield* sql.withTransaction(select).pipe(Effect.sandbox, Effect.flip))
593 // The body succeeds, but the lost COMMIT never runs.
594 assertSqlFailure(
595 yield* sql.withTransaction(sql`SELECT ${2}::int4 AS fresh`).pipe(Effect.sandbox, Effect.flip)
596 )
597​
598 assert.deepStrictEqual(yield* sql.withTransaction(select), [{ value: 1 }])
599 }).pipe(Effect.scoped, Effect.provide(Reactivity.layer)))
600})
601​
602it.layer(PgContainer.layerMakeClientAcquireForStream, { timeout: "30 seconds" })(
603 "PgClient.makeClient acquireForStream",
604 (it) => {
605 it.effect("runs queries while a stream is active", () =>
606 Effect.gen(function*() {
607 const sql = yield* PgClient.PgClient
608 const streamStarted = yield* Deferred.make<void>()
609 const releaseStream = yield* Deferred.make<void>()
610 const streamFiber = yield* sql<{ value: number }>`SELECT generate_series(1, 2) AS value`.stream.pipe(
611 Stream.tap(() =>
612 Effect.andThen(
613 Deferred.succeed(streamStarted, undefined),
614 Deferred.await(releaseStream)
615 )
616 ),
617 Stream.runCollect,
618 Effect.forkScoped
619 )
620​
621 yield* Deferred.await(streamStarted)
622 const rows = yield* sql<{ value: number }>`SELECT 1 AS value`.pipe(
623 Effect.timeoutOrElse({
624 duration: "3 seconds",
625 orElse: () => Effect.fail(new Error("query timed out while stream was active"))
626 })
627 )
628 yield* Deferred.succeed(releaseStream, undefined)
629 yield* Fiber.join(streamFiber)
630​
631 assert.deepStrictEqual(rows, [{ value: 1 }])
632 }).pipe(TestClock.withLive))
633​
634 it.effect("uses a new session for streams", () =>
635 Effect.gen(function*() {
636 const sql = yield* PgClient.PgClient
637 yield* sql`SET application_name = 'sticky-primary'`
638​
639 const rows = yield* sql<{ applicationName: string }>`
640 SELECT current_setting('application_name') AS "applicationName"
641 `.stream.pipe(Stream.runCollect)
642​
643 assert.deepStrictEqual(Array.from(rows), [{ applicationName: "side-default" }])
644 }))
645 }
647​
648it.effect("PgClient.makeClient surfaces transport creation failures", () =>
649 Effect.gen(function*() {
650 const error = yield* Effect.flip(PgClient.makeClient({
651 username: "test",
652 stream: () => {
653 throw new Error("connection failed")
654 }
655 }))
656​
657 assert.strictEqual(error.reason._tag, "ConnectionError")
658 assert.strictEqual(error.reason.operation, "connect")
659 }).pipe(
660 Effect.scoped,
661 Effect.provide(Reactivity.layer)
662 ))
663​
664it.layer(PgContainer.layerClientWithTransforms, { timeout: "30 seconds" })("PgClient transforms", (it) => {
665 it.effect("insert helper", () =>
666 Effect.gen(function*() {
667 const sql = yield* PgClient.PgClient
668 const [query, params] = sql`INSERT INTO people ${sql.insert({ firstName: "Tim", age: 10 })}`.compile()
669 expect(query).toEqual(`INSERT INTO people ("first_name","age") VALUES ($1,$2)`)
670 expect(params).toEqual(["Tim", 10])
671 }))
672​
673 it.effect("insert helper withoutTransforms", () =>
674 Effect.gen(function*() {
675 const sql = (yield* PgClient.PgClient).withoutTransforms()
676 const [query, params] = sql`INSERT INTO people ${sql.insert({ first_name: "Tim", age: 10 })}`.compile()
677 expect(query).toEqual(`INSERT INTO people ("first_name","age") VALUES ($1,$2)`)
678 expect(params).toEqual(["Tim", 10])
679 }))
680​
681 it.effect("rejects multi-statement queries", () =>
682 Effect.gen(function*() {
683 const sql = yield* SqlClient.SqlClient
684​
685 const error = yield* Effect.flip(sql`
686 CREATE TABLE test_multi (id TEXT PRIMARY KEY, name TEXT);
687 SELECT 1;
688 `)
689​
690 assert.strictEqual(error.reason._tag, "SqlSyntaxError")
691 }))
692​
693 it.effect("interruption", () =>
694 Effect.gen(function*() {
695 const sql = yield* SqlClient.SqlClient
696 const conn = yield* sql.reserve
697 yield* conn.executeRaw("select pg_sleep(1000)", []).pipe(
698 Effect.timeoutOption("50 millis"),
699 TestClock.withLive
700 )
701 const value = yield* conn.executeValues("select 1", [])
702 expect(value).toEqual([[1]])
703 }))
704​
705 it.effect("retains the supplied config", () =>
706 Effect.gen(function*() {
707 const sql = yield* PgClient.PgClient
708​
709 assert.isDefined(sql.config.url)
710 expect(sql.config.transformResultNames).toEqual(String.snakeToCamel)
711 expect(sql.config.transformQueryNames).toEqual(String.camelToSnake)
712 }))
713})
714​
715// Each listener uses one of two pool connections.
716it.layer(PgContainer.layerClientForListen, { timeout: "30 seconds", concurrent: false })("PgClient listen", (it) => {
717 it.effect("keeps queries available while a listener reserves one connection", () =>
718 Effect.gen(function*() {
719 const sql = yield* PgClient.PgClient
720 const channel = "pool_connection_listen"
721​
722 const payloads = yield* sql.listen(channel)
723​
724 const rows = yield* sql<{ value: number }>`SELECT 1 as value`.pipe(
725 Effect.timeoutOrElse({
726 duration: "3 seconds",
727 orElse: () => Effect.fail(new Error("query timed out while listener was active"))
728 })
729 )
730 expect(rows).toEqual([{ value: 1 }])
731​
732 yield* sql.notify(channel, "payload")
733 const payload = yield* Queue.take(payloads).pipe(
734 Effect.timeoutOrElse({
735 duration: "3 seconds",
736 orElse: () => Effect.fail(new Error("listener did not receive notification in time"))
737 })
738 )
739 expect(payload.payload).toEqual("payload")
740 }).pipe(TestClock.withLive), { timeout: 20_000 })
741​
742 it.effect("notify sends payload", () =>
743 Effect.gen(function*() {
744 const sql = yield* PgClient.PgClient
745 const channel = "pool_connection_notify"
746​
747 const payloads = yield* sql.listen(channel)
748 yield* sql.notify(channel, "payload")
749​
750 const payload = yield* Queue.take(payloads).pipe(
751 Effect.timeoutOrElse({
752 duration: "3 seconds",
753 orElse: () => Effect.fail(new Error("listener did not receive notification in time"))
754 })
755 )
756 expect(payload.payload).toEqual("payload")
757 }).pipe(TestClock.withLive), { timeout: 20_000 })
758​
759 it.effect("retries a failed listener and receives notifications on a new connection", () =>
760 Effect.gen(function*() {
761 const sql = yield* PgClient.PgClient
762 const channel = "retry_listener"
763 const registered = yield* Queue.unbounded<void>()
764 const consumer = yield* Stream.unwrap(Effect.gen(function*() {
765 const notifications = yield* sql.listen(channel)
766 yield* Queue.offer(registered, undefined)
767 return Stream.fromQueue(notifications)
768 })).pipe(
769 Stream.retry(Schedule.recurs(1)),
770 Stream.runHead,
771 Effect.forkScoped
772 )
773​
774 yield* Queue.take(registered)
775 const [listener] = yield* sql<{ pid: number }>`
776 SELECT pid FROM pg_stat_activity WHERE query = ${`LISTEN "${channel}"`}
777 `
778 assert.isDefined(listener)
779 yield* sql`SELECT pg_terminate_backend(${listener.pid})`
780​
781 // Wait for registration; PostgreSQL does not replay missed notifications.
782 yield* Queue.take(registered)
783 const [replacement] = yield* sql<{ pid: number }>`
784 SELECT pid FROM pg_stat_activity
785 WHERE query = ${`LISTEN "${channel}"`} AND pid <> ${listener.pid}
786 `
787 assert.isDefined(replacement)
788 yield* sql.notify(channel, "after reconnect")
789 const notification = Option.getOrThrow(yield* Fiber.join(consumer))
790 assert.strictEqual(notification.channel, channel)
791 assert.strictEqual(notification.payload, "after reconnect")
792 }), { timeout: 20_000 })
793​
794 it.effect("listen rejects channel names longer than 63 UTF-8 bytes", () =>
795 Effect.gen(function*() {
796 const sql = yield* PgClient.PgClient
797 const error = yield* Effect.flip(sql.listen("é".repeat(32)))
798​
799 assert.strictEqual(error.message, "PostgreSQL channel names must not exceed 63 UTF-8 bytes")
800 assert.strictEqual(error.reason.operation, "listen")
801 }))
802​
803 it.effect("notify rejects channel names longer than 63 UTF-8 bytes", () =>
804 Effect.gen(function*() {
805 const sql = yield* PgClient.PgClient
806 const error = yield* Effect.flip(sql.notify("é".repeat(32), "payload"))
807​
808 assert.strictEqual(error.message, "PostgreSQL channel names must not exceed 63 UTF-8 bytes")
809 assert.strictEqual(error.reason.operation, "notify")
810 }))
811})
812​
813const RequestId = Context.Reference<string>("test/RequestId", { defaultValue: () => "none" })
814​
815class Prefix extends Context.Service<Prefix, string>()("test/Prefix") {}
816​
817it.layer(PgContainer.layer, { timeout: "30 seconds" })("PgClient onAcquire", (it) => {
818 it.effect("runs once per acquisition with construction services in the consuming fiber", () =>
819 Effect.gen(function*() {
820 const container = yield* PgContainer
821 const calls: Array<string> = []
822 const context = yield* Layer.build(
823 PgClient.layer({
824 url: Redacted.make(container.getConnectionUri()),
825 onAcquire: Effect.gen(function*() {
826 calls.push(`${yield* Prefix}:${yield* RequestId}`)
827 })
828 }).pipe(Layer.provide(Layer.succeed(Prefix, "pool")))
829 )
830 const sql = Context.get(context, PgClient.PgClient)
831​
832 yield* sql`SELECT 1`.pipe(Effect.provideService(RequestId, "statement"))
833 yield* sql.withTransaction(Effect.andThen(sql`SELECT 1`, sql`SELECT 2`)).pipe(
834 Effect.provideService(RequestId, "transaction")
835 )
836​
837 assert.deepStrictEqual(calls, ["pool:statement", "pool:transaction"])
838 }).pipe(Effect.scoped))
839​
840 it.effect("closes the hook's scope after each statement", () =>
841 Effect.gen(function*() {
842 const container = yield* PgContainer
843 let finalized = 0
844 const sql = yield* PgClient.make({
845 url: Redacted.make(container.getConnectionUri()),
846 onAcquire: Effect.addFinalizer(() =>
847 Effect.sync(() => {
848 finalized++
849 })
850 )
851 })
852​
853 yield* sql`SELECT 1`
854 yield* sql`SELECT 1`
855​
856 assert.strictEqual(finalized, 2)
857 }).pipe(Effect.scoped, Effect.provide(Reactivity.layer)))
858})