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

PgConnection.integration.test.ts

752 lines34.3 KB

1import { PgConnection, PgTypes } from "@effect/sql-pg"
2import { assert, it } from "@effect/vitest"
3import { Cause, Deferred, Effect, Exit, Fiber, Option, Queue, Redacted, Scheduler, Scope, Stream } from "effect"
4import type { SqlError } from "effect/sql/SqlError"
5import * as TestClock from "effect/testing/TestClock"
6import * as Net from "node:net"
7import { PgContainer, waitUntilActive, waitUntilAdvisoryLock } from "./utils.ts"
8​
9const makeConnection = Effect.fnUntraced(function*(options?: PgConnection.Config) {
10 const container = yield* PgContainer
11 return yield* PgConnection.make({
12 url: Redacted.make(container.getConnectionUri()),
13 ...options
14 })
15})
16​
17const assertInterruptedOnClose = Effect.fnUntraced(function*(
18 scope: Scope.Closeable,
19 notifications: Queue.Dequeue<PgConnection.Notification, SqlError>
20) {
21 const consumer = yield* Effect.forkScoped(Queue.take(notifications))
22 yield* Scope.close(scope, Exit.void)
23 const exit = yield* Fiber.await(consumer)
24 assert.isTrue(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause))
25})
26​
27// Runs a fiber normally until `holding` is set, then queues its tasks and runs
28// them one at a time through `step`, so a test can stop it between two operations.
29class SteppedScheduler implements Scheduler.Scheduler {
30 readonly executionMode = "async"
31 holding = false
32 private readonly fallback = new Scheduler.MixedScheduler()
33 private readonly held: Array<() => void> = []
34 private onHeld: (() => void) | undefined
35​
36 // While holding, yield after one operation; the first operation after a
37 // yield only resumes the yielded continuation.
38 shouldYield(fiber: Fiber.Fiber<unknown, unknown>): boolean {
39 return this.holding ? fiber.currentOpCount > 2 : this.fallback.shouldYield(fiber)
40 }
41​
42 makeDispatcher(): Scheduler.SchedulerDispatcher {
43 const dispatcher = this.fallback.makeDispatcher()
44 return {
45 scheduleTask: (task, priority) => {
46 if (!this.holding) return dispatcher.scheduleTask(task, priority)
47 this.held.push(task)
48 const onHeld = this.onHeld
49 this.onHeld = undefined
50 onHeld?.()
51 },
52 flush: () => dispatcher.flush()
53 }
54 }
55​
56 readonly step: Effect.Effect<void> = Effect.callback((resume) => {
57 const run = () =>
58 setImmediate(() => {
59 this.held.shift()!()
60 resume(Effect.void)
61 })
62 if (this.held.length > 0) run()
63 else this.onHeld = run
64 })
65​
66 release(): void {
67 this.holding = false
68 for (const task of this.held.splice(0)) setImmediate(task)
69 }
71​
72it.layer(PgContainer.layer, { timeout: "30 seconds" })("PgConnection", (it) => {
73 it.effect("interrupts notification consumers when the connection scope closes", () =>
74 Effect.gen(function*() {
75 const scope = yield* Scope.fork(yield* Scope.Scope)
76 const connection = yield* Scope.provide(makeConnection(), scope)
77 const notifications = yield* connection.listen("closed_listener")
78 yield* assertInterruptedOnClose(scope, notifications)
79 }))
80​
81 it.effect("interrupts notification consumers when the listener scope closes", () =>
82 Effect.gen(function*() {
83 const scope = yield* Scope.fork(yield* Scope.Scope)
84 const connection = yield* makeConnection()
85 const notifications = yield* Scope.provide(connection.listen("closed_listener"), scope)
86 yield* assertInterruptedOnClose(scope, notifications)
87 }))
88​
89 it.effect("closes a listener whose connection stops responding", () =>
90 Effect.gen(function*() {
91 const container = yield* PgContainer
92 const sockets: Array<Net.Socket> = []
93 const connection = yield* makeConnection({
94 stream: () => {
95 const socket = Net.connect({ host: container.getHost(), port: container.getMappedPort(5432) })
96 sockets.push(socket)
97 return socket
98 }
99 })
100 const scope = yield* Scope.make()
101 yield* Scope.provide(connection.listen("unanswered_listener"), scope)
102 for (const socket of sockets) socket.pause()
103​
104 const closing = yield* Effect.forkDetach(Scope.close(scope, Exit.void))
105 yield* Effect.gen(function*() {
106 const closed = yield* Fiber.await(closing).pipe(Effect.timeoutOption("10 seconds"))
107 assert.isTrue(Option.isSome(closed), "listener scope did not close within 10 seconds")
108 assert.isTrue(Exit.isFailure(yield* Effect.exit(connection.query("SELECT 1"))))
109 }).pipe(Effect.ensuring(Effect.sync(() => sockets.forEach((socket) => socket.destroy()))))
110 }).pipe(TestClock.withLive), { timeout: 30000 })
111​
112 it.effect("keeps a busy pinned session when a listener closes", () =>
113 Effect.gen(function*() {
114 const connection = yield* makeConnection()
115 const observer = yield* makeConnection()
116 const pinned = yield* connection.pin
117 const scope = yield* Scope.make()
118 yield* Scope.provide(pinned.listen("busy_listener"), scope)
119 const slow = yield* Effect.forkChild(pinned.query("SELECT pg_sleep(6)"))
120 yield* waitUntilActive(observer, pinned.processId)
121​
122 yield* Scope.close(scope, Exit.void)
123 yield* Fiber.join(slow)
124 const result = yield* pinned.query("SELECT 1 AS one")
125 assert.deepStrictEqual(result.rows, [{ one: 1 }])
126 }).pipe(TestClock.withLive), { timeout: 30000 })
127​
128 it.effect("skips UNLISTEN queued behind a pin release", () =>
129 Effect.gen(function*() {
130 const connection = yield* makeConnection()
131 const pinScope = yield* Scope.make()
132 const pinned = yield* Scope.provide(connection.pin, pinScope)
133 const listenScope = yield* Scope.make()
134 yield* Scope.provide(pinned.listen("released_listener"), listenScope)
135 // Release the pin in the same fiber as the statement, so the release
136 // follows the statement's response without waiting on the scheduler.
137 const releasing = yield* Effect.forkChild(
138 Effect.andThen(pinned.query("SELECT pg_sleep(0.05)"), Scope.close(pinScope, Exit.void)),
139 { startImmediately: true }
140 )
141 // Close the listener while the statement holds the wire, queueing
142 // UNLISTEN behind it.
143 const closing = yield* Effect.forkChild(Scope.close(listenScope, Exit.void), { startImmediately: true })
144 yield* Fiber.join(releasing)
145 yield* Fiber.join(closing)
146​
147 const next = yield* Effect.forkDetach(connection.query("SELECT 1 AS one"))
148 const result = yield* Fiber.join(next).pipe(Effect.timeout("2 seconds"))
149 assert.deepStrictEqual(result.rows, [{ one: 1 }])
150 }).pipe(TestClock.withLive))
151​
152 it.effect("waits for an UNLISTEN holding the wire at pin release", () =>
153 Effect.gen(function*() {
154 // Each run has a narrow window, so repeat it to make a regression show up reliably.
155 for (let run = 0; run < 10; run++) {
156 yield* Effect.scoped(Effect.gen(function*() {
157 const connection = yield* makeConnection()
158 const pinScope = yield* Scope.make()
159 const pinned = yield* Scope.provide(connection.pin, pinScope)
160 const listenScope = yield* Scope.make()
161 yield* Scope.provide(pinned.listen("unlistening_listener"), listenScope)
162 const closing = yield* Effect.forkDetach(
163 Effect.andThen(Effect.yieldNow, Scope.close(listenScope, Exit.void))
164 )
165 yield* pinned.query("SELECT pg_sleep(0.05)")
166 // Let the queued UNLISTEN take the wire, so the release lands while
167 // it runs or between its completion and the permit release.
168 yield* Effect.yieldNow
169 yield* Effect.yieldNow
170 yield* Effect.yieldNow
171​
172 yield* Scope.close(pinScope, Exit.void)
173 const next = yield* Effect.forkDetach(connection.query("SELECT 1 AS one"))
174 const result = yield* Fiber.join(next).pipe(Effect.timeout("2 seconds"))
175 assert.deepStrictEqual(result.rows, [{ one: 1 }])
176 yield* Fiber.join(closing)
177 }))
178 }
179 }).pipe(TestClock.withLive, Effect.provideService(Scheduler.MaxOpsBeforeYield, 5)))
180​
181 it.effect("does not wait for ordinary work that overtakes UNLISTEN at pin release", () =>
182 Effect.gen(function*() {
183 const container = yield* PgContainer
184 const sockets: Array<Net.Socket> = []
185 const written: Array<string> = []
186 const connection = yield* makeConnection({
187 stream: () => {
188 const socket = Net.connect({ host: container.getHost(), port: container.getMappedPort(5432) })
189 const write = socket.write.bind(socket) as (chunk: Uint8Array) => boolean
190 socket.write = ((chunk: Uint8Array) => {
191 written.push(Buffer.from(chunk).toString("latin1"))
192 return write(chunk)
193 }) as typeof socket.write
194 sockets.push(socket)
195 return socket
196 }
197 })
198 const sent = (text: string) => written.some((frame) => frame.includes(text))
199 const pinScope = yield* Scope.make()
200 const pinned = yield* Scope.provide(connection.pin, pinScope)
201 const listenScope = yield* Scope.make()
202 yield* Scope.provide(pinned.listen("overtaken_listener"), listenScope)
203​
204 yield* Effect.gen(function*() {
205 // Hold the UNLISTEN reply so the cleanup keeps the wire.
206 for (const socket of sockets) socket.pause()
207 const scheduler = new SteppedScheduler()
208 const closing = yield* Effect.forkDetach(Scope.close(listenScope, Exit.void)).pipe(
209 Effect.provideService(Scheduler.Scheduler, scheduler)
210 )
211 while (!sent("UNLISTEN")) yield* Effect.yieldNow
212 const overtaking = yield* Effect.forkDetach(pinned.query("SELECT pg_sleep(30)"))
213 // The forked query queues on the wire before this fiber resumes.
214 yield* Effect.yieldNow
215​
216 // Step the cleanup until the wire passes to the queued query, leaving
217 // the rest of the cleanup unrun.
218 scheduler.holding = true
219 for (const socket of sockets) socket.resume()
220 while (!sent("pg_sleep(30)")) yield* scheduler.step
221​
222 const releasing = yield* Effect.forkDetach(Scope.close(pinScope, Exit.void))
223 scheduler.release()
224 const released = yield* Fiber.await(releasing).pipe(Effect.timeoutOption("2 seconds"))
225 assert.isTrue(Option.isSome(released), "pin release waited for the overtaking query")
226 assert.isTrue(Exit.isFailure(yield* Fiber.await(overtaking)))
227 yield* Fiber.join(closing)
228 }).pipe(Effect.ensuring(Effect.sync(() => sockets.forEach((socket) => socket.destroy()))))
229 }).pipe(TestClock.withLive), { timeout: 30000 })
230​
231 it.effect("connects through ReadyForQuery", () =>
232 Effect.gen(function*() {
233 const connection = yield* makeConnection()
234 assert.isAbove(connection.processId, 0)
235 }))
236​
237 it.effect("runs unnamed extended queries with inferred binary parameters", () =>
238 Effect.gen(function*() {
239 const connection = yield* makeConnection()
240 const instant = new Date("2024-05-06T07:08:09.123Z")
241 const result = yield* connection.query(
242 "SELECT $1::int4 AS i, $2::float8 AS f, $3::int8 AS b, $4::bool AS flag, " +
243 "$5::text AS text, $6::bytea AS bytes, $7::timestamptz AS instant, " +
244 "$8::int4[] AS numbers, $9::text AS nil, $10::jsonb AS jsonb",
245 [
246 1,
247 1.5,
248 BigInt(2),
249 true,
250 "hello",
251 new Int8Array([1, -1]),
252 instant,
253 [1, null, 3],
254 null,
255 PgTypes.jsonb({ nested: true })
256 ]
257 )
258 assert.strictEqual(result.command, "SELECT")
259 assert.strictEqual(result.rowCount, 1)
260 assert.strictEqual(result.oid, null)
261 assert.deepStrictEqual(result.rows, [{
262 i: 1,
263 f: 1.5,
264 b: BigInt(2),
265 flag: true,
266 text: "hello",
267 bytes: new Uint8Array([1, 255]),
268 instant,
269 numbers: [1, null, 3],
270 nil: null,
271 jsonb: { nested: true }
272 }])
273 assert.deepStrictEqual(result.fields.map((field) => field.name), [
274 "i",
275 "f",
276 "b",
277 "flag",
278 "text",
279 "bytes",
280 "instant",
281 "numbers",
282 "nil",
283 "jsonb"
284 ])
285 }))
286​
287 it.effect("applies the session TimeZone only to Dates bound into timestamp columns", () =>
288 Effect.gen(function*() {
289 const connection = yield* makeConnection()
290 const instant = new Date("2024-05-06T07:08:09.123Z")
291 yield* connection.query(
292 "CREATE TEMP TABLE timestamp_timezone (bare timestamp, explicit timestamp, zoned timestamptz)"
293 )
294 for (
295 const [zone, expectedBare] of [
296 ["UTC", instant],
297 ["Europe/Berlin", new Date("2024-05-06T09:08:09.123Z")]
298 ] as const
299 ) {
300 yield* connection.query(`SET TIME ZONE '${zone}'`)
301 yield* connection.query("TRUNCATE timestamp_timezone")
302 yield* connection.query(
303 "INSERT INTO timestamp_timezone VALUES ($1, $2, $3)",
304 [instant, PgTypes.timestamp(instant), instant]
305 )
306 const result = yield* connection.query("SELECT * FROM timestamp_timezone")
307 assert.deepStrictEqual(result.rows, [{ bare: expectedBare, explicit: instant, zoned: instant }])
308 }
309 }))
310​
311 it.effect("returns queryValues in RowDescription order", () =>
312 Effect.gen(function*() {
313 const connection = yield* makeConnection()
314 const rows = yield* connection.queryValues(
315 "SELECT $1::int8 AS second, $2::text AS first",
316 [PgTypes.int8(BigInt(7)), "value"]
317 )
318 assert.deepStrictEqual(rows, [[BigInt(7), "value"]])
319 }))
320​
321 it.effect("drains query errors and keeps the connection usable", () =>
322 Effect.gen(function*() {
323 const connection = yield* makeConnection()
324 yield* connection.query("CREATE TEMP TABLE pg_connection_unique (value int4 UNIQUE)")
325 yield* connection.query("INSERT INTO pg_connection_unique VALUES ($1)", [1])
326 const error = yield* Effect.flip(connection.query("INSERT INTO pg_connection_unique VALUES ($1)", [1]))
327 assert.strictEqual(error.reason._tag, "UniqueViolation")
328 if (error.reason._tag === "UniqueViolation") {
329 assert.include(error.reason.constraint, "pg_connection_unique")
330 }
331 const result = yield* connection.query("SELECT count(*)::int8 AS count FROM pg_connection_unique")
332 assert.deepStrictEqual(result.rows, [{ count: BigInt(1) }])
333 }))
334​
335 it.effect("fails rows it cannot decode and keeps the connection usable", () =>
336 Effect.gen(function*() {
337 const connection = yield* makeConnection()
338 const pid = connection.queryValues("SELECT pg_backend_pid()")
339 const before = yield* pid
340 // `point` has no codec: `(0,0)` is sixteen NUL bytes and `(1,2)` is invalid UTF-8.
341 for (const point of ["(0,0)", "(1,2)"]) {
342 const error = yield* connection.query(`SELECT '${point}'::point AS location`).pipe(
343 Effect.andThen((result) => Effect.die(`${point} decoded as ${JSON.stringify(result.rows)}`)),
344 Effect.flip
345 )
346 assert.instanceOf(error.reason.cause, PgTypes.CodecError)
347 assert.include((error.reason.cause as PgTypes.CodecError).message, "location")
348 }
349 assert.deepStrictEqual(yield* pid, before)
350 }))
351​
352 it.effect("binds untyped strings and integers beyond int4", () =>
353 Effect.gen(function*() {
354 const connection = yield* makeConnection()
355 yield* connection.query("CREATE TEMP TABLE inference_widening (id bigint, at timestamptz)")
356 yield* connection.query(
357 "INSERT INTO inference_widening (id, at) VALUES ($1, $2)",
358 ["12345678901234", "2024-05-06T07:08:09Z"]
359 )
360 yield* connection.query("INSERT INTO inference_widening (id) VALUES ($1)", [1755000000000])
361 const rows = yield* connection.queryValues("SELECT id FROM inference_widening ORDER BY id")
362 assert.deepStrictEqual(rows.map((row) => row[0]), [BigInt(1755000000000), BigInt("12345678901234")])
363 }))
364​
365 it.effect("reparses a statement whose first execution failed at bind", () =>
366 Effect.gen(function*() {
367 const connection = yield* makeConnection()
368 const missing = yield* Effect.flip(connection.query("select $1::regclass", ["prepared_bind_failure"]))
369 assert.strictEqual(missing.reason._tag, "SqlSyntaxError")
370 yield* connection.query("CREATE TEMP TABLE prepared_bind_failure (id int)")
371 const found = yield* connection.query("select $1::regclass AS rel", ["prepared_bind_failure"])
372 assert.strictEqual(found.rows.length, 1)
373 }))
374​
375 it.effect("fails with AuthenticationError on a bad password", () =>
376 Effect.gen(function*() {
377 const container = yield* PgContainer
378 const error = yield* Effect.flip(PgConnection.make({
379 host: container.getHost(),
380 port: container.getMappedPort(5432),
381 username: container.getUsername(),
382 password: Redacted.make("definitely-wrong"),
383 database: container.getDatabase()
384 }))
385 assert.strictEqual(error._tag, "SqlError")
386 assert.strictEqual(error.reason._tag, "AuthenticationError")
387 }))
388​
389 it.effect("fails when the server refuses TLS", () =>
390 Effect.gen(function*() {
391 const container = yield* PgContainer
392 const error = yield* Effect.flip(PgConnection.make({
393 host: container.getHost(),
394 port: container.getMappedPort(5432),
395 username: container.getUsername(),
396 password: Redacted.make(container.getPassword()),
397 database: container.getDatabase(),
398 ssl: true
399 }))
400 assert.strictEqual(error.reason._tag, "ConnectionError")
401 assert.include(error.reason.message, "refused TLS")
402 }))
403 it.effect("reuses a prepared statement and keeps its columns", () =>
404 Effect.gen(function*() {
405 const connection = yield* makeConnection()
406 for (let index = 0; index < 3; index++) {
407 const result = yield* connection.query("SELECT $1::int4 AS value, $2::text AS label", [index, "x"])
408 assert.deepStrictEqual(result.rows, [{ value: index, label: "x" }])
409 assert.deepStrictEqual(result.fields, [
410 { name: "value", dataTypeId: 23 },
411 { name: "label", dataTypeId: 25 }
412 ])
413 }
414 const prepared = yield* connection.query("SELECT count(*)::int4 AS n FROM pg_prepared_statements")
415 assert.deepStrictEqual(prepared.rows[0], { n: 2 })
416 }))
417​
418 it.effect("prepares the same text once per parameter signature", () =>
419 Effect.gen(function*() {
420 const connection = yield* makeConnection()
421 assert.deepStrictEqual((yield* connection.query("SELECT $1 AS v", [1])).rows, [{ v: 1 }])
422 assert.deepStrictEqual((yield* connection.query("SELECT $1 AS v", [BigInt(2)])).rows, [{ v: BigInt(2) }])
423 const types = yield* connection.query(
424 "SELECT parameter_types::text AS t FROM pg_prepared_statements WHERE statement = 'SELECT $1 AS v' ORDER BY t"
425 )
426 assert.deepStrictEqual(types.rows, [{ t: "{bigint}" }, { t: "{integer}" }])
427 }))
428​
429 it.effect("re-parses a statement whose result type changed", () =>
430 Effect.gen(function*() {
431 const connection = yield* makeConnection()
432 yield* connection.query("CREATE TEMP TABLE shifting (a int)")
433 yield* connection.query("INSERT INTO shifting VALUES (1)")
434 assert.deepStrictEqual((yield* connection.query("SELECT * FROM shifting")).rows, [{ a: 1 }])
435 yield* connection.query("ALTER TABLE shifting ADD COLUMN b text DEFAULT 'added'")
436 const after = yield* connection.query("SELECT * FROM shifting")
437 assert.deepStrictEqual(after.rows, [{ a: 1, b: "added" }])
438 assert.deepStrictEqual(after.fields, [
439 { name: "a", dataTypeId: 23 },
440 { name: "b", dataTypeId: 25 }
441 ])
442 }))
443​
444 it.effect("re-parses a statement the backend no longer holds", () =>
445 Effect.gen(function*() {
446 const connection = yield* makeConnection()
447 assert.deepStrictEqual((yield* connection.query("SELECT $1::int4 AS n", [7])).rows, [{ n: 7 }])
448 yield* connection.query("DEALLOCATE ALL")
449 assert.deepStrictEqual((yield* connection.query("SELECT $1::int4 AS n", [8])).rows, [{ n: 8 }])
450 }))
451​
452 it.effect("preserves a stale-plan error in a transaction and reparses after rollback", () =>
453 Effect.gen(function*() {
454 const connection = yield* makeConnection()
455 yield* connection.query("CREATE TEMP TABLE stale_in_transaction (a int4)")
456 yield* connection.query("INSERT INTO stale_in_transaction VALUES (1)")
457 yield* connection.query("SELECT * FROM stale_in_transaction")
458 yield* connection.query("ALTER TABLE stale_in_transaction ADD COLUMN b text DEFAULT 'added'")
459 yield* connection.query("BEGIN")
460 const error = yield* Effect.flip(connection.query("SELECT * FROM stale_in_transaction"))
461 assert.propertyVal(error.reason.cause, "code", "0A000")
462 yield* connection.query("ROLLBACK")
463 assert.deepStrictEqual((yield* connection.query("SELECT * FROM stale_in_transaction")).rows, [{
464 a: 1,
465 b: "added"
466 }])
467 }))
468​
469 it.effect("preserves a missing-statement error in a transaction and reparses after rollback", () =>
470 Effect.gen(function*() {
471 const connection = yield* makeConnection()
472 yield* connection.query("SELECT $1::int4 AS n", [7])
473 yield* connection.query("DEALLOCATE ALL")
474 yield* connection.query("BEGIN")
475 const error = yield* Effect.flip(connection.query("SELECT $1::int4 AS n", [8]))
476 assert.propertyVal(error.reason.cause, "code", "26000")
477 yield* connection.query("ROLLBACK")
478 assert.deepStrictEqual((yield* connection.query("SELECT $1::int4 AS n", [9])).rows, [{ n: 9 }])
479 }))
480​
481 it.effect("closes statements it evicts from a full cache", () =>
482 Effect.gen(function*() {
483 const connection = yield* makeConnection({ preparedStatementCacheSize: 3 })
484 for (let round = 0; round < 2; round++) {
485 for (let index = 0; index < 8; index++) {
486 const result = yield* connection.query(`SELECT ${index}::int4 AS n, $1::text AS t`, ["v"])
487 assert.deepStrictEqual(result.rows, [{ n: index, t: "v" }])
488 }
489 }
490 const held = yield* connection.query("SELECT count(*)::int4 AS n FROM pg_prepared_statements")
491 assert.deepStrictEqual(held.rows[0], { n: 3 })
492 }))
493​
494 it.effect("closes statements parsed while a pipeline overfills the cache", () =>
495 Effect.gen(function*() {
496 const connection = yield* makeConnection({ preparedStatementCacheSize: 1, multiplex: true })
497 yield* Effect.all(
498 Array.from({ length: 4 }, (_, index) => connection.query(`SELECT ${index}::int4 AS n`)),
499 { concurrency: "unbounded" }
500 )
501 const held = yield* connection.query("SELECT count(*)::int4 AS n FROM pg_prepared_statements")
502 assert.deepStrictEqual(held.rows[0], { n: 1 })
503 }))
504​
505 it.effect("parses every statement when prepare is off", () =>
506 Effect.gen(function*() {
507 const connection = yield* makeConnection({ prepare: false })
508 for (let index = 0; index < 3; index++) {
509 assert.deepStrictEqual((yield* connection.query("SELECT $1::int4 AS n", [index])).rows, [{ n: index }])
510 }
511 const held = yield* connection.query("SELECT count(*)::int4 AS n FROM pg_prepared_statements")
512 assert.deepStrictEqual(held.rows[0], { n: 0 })
513 }))
514​
515 it.effect("stays usable after a statement the server refuses to parse", () =>
516 Effect.gen(function*() {
517 const connection = yield* makeConnection()
518 const missing = yield* Effect.flip(connection.query("SELECT * FROM does_not_exist"))
519 assert.strictEqual(missing.reason._tag, "SqlSyntaxError")
520 const syntax = yield* Effect.flip(connection.query("SELECT FROM WHERE ????"))
521 assert.strictEqual(syntax.reason._tag, "SqlSyntaxError")
522 assert.deepStrictEqual((yield* connection.query("SELECT 42::int4 AS answer")).rows, [{ answer: 42 }])
523 }))
524 it.effect("closes a statement whose plan it had to throw away", () =>
525 Effect.gen(function*() {
526 const connection = yield* makeConnection()
527 yield* connection.query("CREATE TEMP TABLE churn (a int)")
528 for (let round = 0; round < 4; round++) {
529 yield* connection.query("SELECT * FROM churn")
530 yield* connection.query(`ALTER TABLE churn ADD COLUMN c${round} text`)
531 }
532 yield* connection.query("SELECT * FROM churn")
533 // Every re-parse after a stale plan has to close the name it replaced,
534 // or each DDL change strands a statement on the backend.
535 const held = yield* connection.query(
536 "SELECT count(*)::int4 AS n FROM pg_prepared_statements WHERE statement = 'SELECT * FROM churn'"
537 )
538 assert.deepStrictEqual(held.rows[0], { n: 1 })
539 }))
540 it.effect("re-parses a statement first prepared in a rolled back transaction", () =>
541 Effect.gen(function*() {
542 const connection = yield* makeConnection()
543 yield* connection.query("CREATE TEMP TABLE rolled_back (a int)")
544​
545 // Postgres drops a statement prepared inside a transaction it rolls
546 // back, so the cached name is gone even though the session lives on.
547 yield* connection.query("BEGIN")
548 yield* connection.query("INSERT INTO rolled_back VALUES ($1::int4)", [1])
549 yield* connection.query("ROLLBACK")
550​
551 yield* connection.query("INSERT INTO rolled_back VALUES ($1::int4)", [2])
552 yield* connection.query("INSERT INTO rolled_back VALUES ($1::int4)", [3])
553 assert.deepStrictEqual(
554 (yield* connection.query("SELECT a FROM rolled_back ORDER BY a")).rows,
555 [{ a: 2 }, { a: 3 }]
556 )
557 }))
558 it.effect("isolates errors between pipelined queries", () =>
559 Effect.gen(function*() {
560 const connection = yield* makeConnection({ multiplex: true })
561 const exits = yield* Effect.all([
562 Effect.exit(connection.query("SELECT $1::int4 AS first", [1])),
563 Effect.exit(connection.query("SELECT missing_pipeline_column")),
564 Effect.exit(connection.query("SELECT $1::int4 AS third", [3]))
565 ], { concurrency: "unbounded" })
566​
567 assert.strictEqual(exits[0]._tag, "Success")
568 assert.strictEqual(exits[1]._tag, "Failure")
569 assert.strictEqual(exits[2]._tag, "Success")
570 if (exits[0]._tag === "Success") assert.deepStrictEqual(exits[0].value.rows, [{ first: 1 }])
571 if (exits[2]._tag === "Success") assert.deepStrictEqual(exits[2].value.rows, [{ third: 3 }])
572 }))
573​
574 it.effect("isolates a pipelined query whose rows cannot be decoded", () =>
575 Effect.gen(function*() {
576 const connection = yield* makeConnection({ multiplex: true })
577 const exits = yield* Effect.all([
578 Effect.exit(connection.query("SELECT $1::int4 AS first", [1])),
579 Effect.exit(connection.query("SELECT point(n, n) AS location FROM generate_series(0, 2) AS n")),
580 Effect.exit(connection.query("SELECT $1::int4 AS third", [3]))
581 ], { concurrency: "unbounded" })
582​
583 assert.strictEqual(exits[0]._tag, "Success")
584 assert.strictEqual(exits[1]._tag, "Failure")
585 assert.strictEqual(exits[2]._tag, "Success")
586 if (exits[0]._tag === "Success") assert.deepStrictEqual(exits[0].value.rows, [{ first: 1 }])
587 if (exits[1]._tag === "Failure") {
588 const error = Cause.squash(exits[1].cause) as SqlError
589 assert.instanceOf(error.reason.cause, PgTypes.CodecError)
590 assert.include((error.reason.cause as PgTypes.CodecError).message, "location")
591 }
592 if (exits[2]._tag === "Success") assert.deepStrictEqual(exits[2].value.rows, [{ third: 3 }])
593 }))
594​
595 it.effect("drains an interrupted pipelined query without cancelling its neighbors", () =>
596 Effect.gen(function*() {
597 const connection = yield* makeConnection({ multiplex: true })
598 const first = yield* connection.query("SELECT pg_sleep(0.05), 1 AS first").pipe(Effect.forkScoped)
599 const second = yield* connection.query("SELECT 2 AS second").pipe(Effect.forkScoped)
600 yield* Effect.yieldNow
601 yield* Fiber.interrupt(first)
602​
603 const result = yield* Fiber.join(second)
604 assert.deepStrictEqual(result.rows, [{ second: 2 }])
605 assert.deepStrictEqual((yield* connection.query("SELECT 3 AS after")).rows, [{ after: 3 }])
606 }))
607​
608 it.effect("places pin requests between earlier and later pipelined queries", () =>
609 Effect.gen(function*() {
610 const connection = yield* makeConnection({ multiplex: true })
611 yield* connection.query(
612 "CREATE TEMP TABLE pipeline_pin_order (position int GENERATED ALWAYS AS IDENTITY, value int4)"
613 )
614 const first = yield* connection.query(
615 "INSERT INTO pipeline_pin_order (value) SELECT 1 FROM pg_sleep(0.05)"
616 ).pipe(Effect.forkScoped)
617 yield* Effect.yieldNow
618​
619 const pinned = yield* Deferred.make<void>()
620 const release = yield* Deferred.make<void>()
621 const pinFiber = yield* Effect.scoped(Effect.gen(function*() {
622 const exclusive = yield* connection.pin
623 yield* exclusive.query("INSERT INTO pipeline_pin_order (value) VALUES (2)")
624 yield* Deferred.succeed(pinned, undefined)
625 yield* Deferred.await(release)
626 })).pipe(Effect.forkScoped)
627 yield* Effect.yieldNow
628 const third = yield* connection.query("INSERT INTO pipeline_pin_order (value) VALUES (3)").pipe(
629 Effect.forkScoped
630 )
631​
632 yield* Deferred.await(pinned)
633 assert.isUndefined(third.pollUnsafe())
634 yield* Deferred.succeed(release, undefined)
635 yield* Fiber.join(first)
636 yield* Fiber.join(pinFiber)
637 yield* Fiber.join(third)
638​
639 const result = yield* connection.query("SELECT value FROM pipeline_pin_order ORDER BY position")
640 assert.deepStrictEqual(result.rows, [{ value: 1 }, { value: 2 }, { value: 3 }])
641 }))
642​
643 it.effect("reuses prepared statements across a pipeline", () =>
644 Effect.gen(function*() {
645 const connection = yield* makeConnection({ multiplex: true })
646 for (let round = 0; round < 3; round++) {
647 const results = yield* Effect.all(
648 Array.from({ length: 8 }, (_, index) => connection.query("SELECT $1::int4 AS n", [index])),
649 { concurrency: "unbounded" }
650 )
651 results.forEach((result, index) => assert.deepStrictEqual(result.rows, [{ n: index }]))
652 }
653 const held = yield* connection.query(
654 "SELECT count(*)::int4 AS n FROM pg_prepared_statements WHERE statement = 'SELECT $1::int4 AS n'"
655 )
656 assert.deepStrictEqual(held.rows[0], { n: 1 })
657 }))
658 it.effect("orders ordinary statements against a stream on the same session", () =>
659 Effect.gen(function*() {
660 const connection = yield* makeConnection()
661 // An ordinary statement holds `owner` rather than the wire permit, so
662 // this is what says it still cannot interleave with a stream, which
663 // reaches the session through a pin.
664 const streamed = yield* Effect.forkScoped(
665 Stream.runCollect(connection.stream("SELECT generate_series(1, 200) AS n"))
666 )
667 const queried = yield* Effect.forkScoped(
668 Effect.all(
669 Array.from({ length: 12 }, (_, index) => connection.query("SELECT $1::int4 AS n", [index])),
670 { concurrency: "unbounded" }
671 )
672 )
673 const rows = yield* Fiber.join(streamed)
674 assert.strictEqual(Array.from(rows).length, 200)
675 const results = yield* Fiber.join(queried)
676 results.forEach((result, index) => assert.deepStrictEqual(result.rows, [{ n: index }]))
677 assert.deepStrictEqual((yield* connection.query("SELECT 1 AS ok")).rows, [{ ok: 1 }])
678 }))
679​
680 it.effect("fails a stream whose rows cannot be decoded and keeps the connection usable", () =>
681 Effect.gen(function*() {
682 const connection = yield* makeConnection()
683 const pid = connection.queryValues("SELECT pg_backend_pid()")
684 const before = yield* pid
685 const error = yield* Stream.runCollect(
686 connection.stream("SELECT point(n, n) AS location FROM generate_series(0, 2) AS n")
687 ).pipe(
688 Effect.andThen((rows) => Effect.die(`stream decoded as ${JSON.stringify(Array.from(rows))}`)),
689 Effect.flip
690 )
691 assert.instanceOf(error.reason.cause, PgTypes.CodecError)
692 assert.include((error.reason.cause as PgTypes.CodecError).message, "location")
693 assert.deepStrictEqual(yield* pid, before)
694 }))
695​
696 it.effect("fails work through a released pin without touching the next owner's session", () =>
697 Effect.gen(function*() {
698 const connection = yield* makeConnection()
699 const released = yield* Effect.scoped(connection.pin)
700 yield* Effect.scoped(Effect.gen(function*() {
701 const owner = yield* connection.pin
702 yield* owner.query("BEGIN")
703 yield* owner.query("SET LOCAL application_name = 'next_owner'")
704​
705 const exits: ReadonlyArray<Exit.Exit<unknown, SqlError>> = [
706 yield* Effect.exit(released.query("ROLLBACK")),
707 yield* Effect.exit(released.queryValues("ROLLBACK")),
708 yield* Effect.exit(Stream.runCollect(released.stream("SELECT 1"))),
709 yield* Effect.exit(Effect.scoped(released.listen("released_pin")))
710 ]
711 exits.forEach((exit) => assert.isTrue(Exit.isFailure(exit)))
712​
713 const setting = yield* owner.query("SELECT current_setting('application_name') AS name")
714 assert.deepStrictEqual(setting.rows, [{ name: "next_owner" }])
715 yield* owner.query("ROLLBACK")
716 }))
717 }))
718​
719 it.effect("fails a statement that was queued on a pin before its release", () =>
720 Effect.gen(function*() {
721 const connection = yield* makeConnection()
722 const scope = yield* Scope.make()
723 const pinned = yield* Scope.provide(connection.pin, scope)
724 const queued = yield* Effect.forkScoped(Effect.andThen(Effect.yieldNow, pinned.query("SELECT 1 AS queued")))
725 // `queued` waits for the wire behind this statement, and the pin is
726 // released before it wakes, so the session is idle and handed on.
727 yield* pinned.query("SELECT 1 AS holder")
728 yield* Scope.close(scope, Exit.void)
729 assert.isTrue(Exit.isFailure(yield* Fiber.await(queued)))
730 assert.deepStrictEqual((yield* connection.query("SELECT 1 AS ok")).rows, [{ ok: 1 }])
731 }))
732​
733 it.effect("ignores interrupt on a released pin", () =>
734 Effect.gen(function*() {
735 const connection = yield* makeConnection()
736 const blocker = yield* makeConnection()
737 const observer = yield* makeConnection()
738 const released = yield* Effect.scoped(connection.pin)
739 const waiting = yield* Effect.gen(function*() {
740 yield* blocker.query("BEGIN")
741 yield* blocker.query("SELECT pg_advisory_xact_lock($1::int4)", [connection.processId])
742 const waiting = yield* Effect.forkScoped(
743 connection.query("SELECT pg_advisory_xact_lock($1::int4)", [connection.processId])
744 )
745 // A cancel only lands while the backend is executing, so wait for the lock.
746 yield* waitUntilAdvisoryLock(observer, connection.processId)
747 yield* released.interrupt
748 return waiting
749 }).pipe(Effect.ensuring(Effect.ignore(blocker.query("ROLLBACK"))))
750 assert.isTrue(Exit.isSuccess(yield* Fiber.await(waiting)))
751 }))
752})