The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { PgClient } from "@effect/sql-pg" |
| 2 | import { assert, expect, it } from "@effect/vitest" |
| 3 | import { |
| 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" |
| 19 | import * as Reactivity from "effect/reactivity/Reactivity" |
| 20 | import { Model } from "effect/schema" |
| 21 | import { SqlClient, SqlError, SqlModel } from "effect/sql" |
| 22 | import * as Statement from "effect/sql/Statement" |
| 23 | import { TestClock } from "effect/testing" |
| 24 | import { PgContainer } from "./utils.ts" |
| 25 | |
| 26 | const compilerTransform = PgClient.makeCompiler(String.camelToSnake) |
| 27 | const transformsNested = Statement.defaultTransforms(String.snakeToCamel) |
| 28 | const transforms = Statement.defaultTransforms(String.snakeToCamel, false) |
| 29 | |
| 30 | it.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 bytea as Uint8Array", () => |
| 308 | Effect.gen(function*() { |
| 309 | const sql = yield* PgClient.PgClient |
| 310 | const payload = new Uint8Array([0, 1, 254, 255]) |
| 311 | const rows = yield* sql`SELECT ${payload}::bytea AS payload` |
| 312 | assert.instanceOf(rows[0].payload, Uint8Array) |
| 313 | assert.deepStrictEqual(rows, [{ payload }]) |
| 314 | })) |
| 315 | |
| 316 | it.effect("stream", () => |
| 317 | Effect.gen(function*() { |
| 318 | const sql = yield* SqlClient.SqlClient |
| 319 | const rows = yield* sql`SELECT generate_series(1, 3)`.stream.pipe( |
| 320 | Stream.runCollect |
| 321 | ) |
| 322 | expect(rows).toEqual([ |
| 323 | { "generate_series": 1 }, |
| 324 | { "generate_series": 2 }, |
| 325 | { "generate_series": 3 } |
| 326 | ]) |
| 327 | })) |
| 328 | |
| 329 | it.effect("releases completed nested transaction locks", () => |
| 330 | Effect.gen(function*() { |
| 331 | const sql = yield* PgClient.PgClient |
| 332 | const locks = sql`SELECT count(*)::integer AS count FROM pg_locks |
| 333 | WHERE pid = pg_backend_pid() AND locktype = 'transactionid'` |
| 334 | yield* sql.withTransaction(Effect.gen(function*() { |
| 335 | yield* sql`CREATE TEMP TABLE savepoint_locks (value INTEGER) ON COMMIT DROP` |
| 336 | |
| 337 | yield* sql.withTransaction(sql`INSERT INTO savepoint_locks VALUES (1)`) |
| 338 | assert.deepStrictEqual(yield* locks, [{ count: 1 }]) |
| 339 | |
| 340 | const error = yield* sql.withTransaction( |
| 341 | sql`INSERT INTO savepoint_locks VALUES (2)`.pipe(Effect.andThen(Effect.fail("rollback"))) |
| 342 | ).pipe(Effect.flip) |
| 343 | assert.strictEqual(error, "rollback") |
| 344 | assert.deepStrictEqual(yield* locks, [{ count: 1 }]) |
| 345 | |
| 346 | assert.deepStrictEqual(yield* sql`SELECT value FROM savepoint_locks`, [{ value: 1 }]) |
| 347 | })) |
| 348 | })) |
| 349 | |
| 350 | it.effect("preserves successful concurrent nested transactions", () => |
| 351 | Effect.gen(function*() { |
| 352 | const sql = yield* PgClient.PgClient |
| 353 | const firstStarted = yield* Deferred.make<void>() |
| 354 | const firstInserted = yield* Deferred.make<void>() |
| 355 | |
| 356 | const rows = yield* sql.withTransaction( |
| 357 | Effect.gen(function*() { |
| 358 | yield* sql`CREATE TEMP TABLE nested_transactions (value TEXT) ON COMMIT DROP` |
| 359 | yield* Effect.all([ |
| 360 | sql.withTransaction( |
| 361 | Effect.gen(function*() { |
| 362 | yield* Deferred.succeed(firstStarted, undefined) |
| 363 | yield* Effect.sleep("100 millis") |
| 364 | yield* sql`INSERT INTO nested_transactions VALUES ('first')` |
| 365 | yield* Deferred.succeed(firstInserted, undefined) |
| 366 | }) |
| 367 | ), |
| 368 | Deferred.await(firstStarted).pipe( |
| 369 | Effect.andThen(sql.withTransaction( |
| 370 | Deferred.await(firstInserted).pipe( |
| 371 | Effect.andThen(Effect.fail("rollback")) |
| 372 | ) |
| 373 | )) |
| 374 | ) |
| 375 | ], { concurrency: "unbounded" }).pipe(Effect.catch(() => Effect.void)) |
| 376 | return yield* sql<{ value: string }>`SELECT value FROM nested_transactions` |
| 377 | }) |
| 378 | ) |
| 379 | |
| 380 | assert.deepStrictEqual(rows, [{ value: "first" }]) |
| 381 | }).pipe(TestClock.withLive)) |
| 382 | |
| 383 | it.effect("fails a transaction whose COMMIT rolls back after a caught error", () => |
| 384 | Effect.gen(function*() { |
| 385 | const sql = yield* PgClient.PgClient |
| 386 | const cause = yield* sql.withTransaction(Effect.gen(function*() { |
| 387 | yield* Effect.ignore(sql`SELECT 1 / 0`) |
| 388 | })).pipe(Effect.sandbox, Effect.flip) |
| 389 | |
| 390 | assert.isFalse(Cause.hasDies(cause)) |
| 391 | assert.isTrue(Cause.hasFails(cause)) |
| 392 | const error = Cause.squash(cause) |
| 393 | assert.instanceOf(error, SqlError.SqlError) |
| 394 | assert.strictEqual(error.reason._tag, "UnknownError") |
| 395 | assert.strictEqual(error.reason.operation, "commit") |
| 396 | })) |
| 397 | |
| 398 | it.effect("afterCommit runs once other connections see the transaction's rows", () => |
| 399 | Effect.gen(function*() { |
| 400 | const sql = yield* PgClient.PgClient |
| 401 | yield* sql`CREATE TABLE after_commit_visibility (value INTEGER)` |
| 402 | let seen: ReadonlyArray<{ readonly count: number }> = [] |
| 403 | |
| 404 | yield* sql.withTransaction(Effect.gen(function*() { |
| 405 | yield* sql`INSERT INTO after_commit_visibility VALUES (1)` |
| 406 | yield* sql.afterCommit( |
| 407 | sql<{ count: number }>`SELECT count(*)::integer AS count FROM after_commit_visibility`.pipe( |
| 408 | Effect.map((rows) => { |
| 409 | seen = rows |
| 410 | }), |
| 411 | Effect.orDie |
| 412 | ) |
| 413 | ) |
| 414 | })) |
| 415 | |
| 416 | assert.deepStrictEqual(seen, [{ count: 1 }]) |
| 417 | })) |
| 418 | }) |
| 419 | |
| 420 | it.layer(PgContainer.layerMakeClientUnprepared, { timeout: "30 seconds" })( |
| 421 | "PgClient.makeClient without preparation", |
| 422 | (it) => { |
| 423 | it.effect("fails an aborted COMMIT and reuses the connection", () => |
| 424 | Effect.gen(function*() { |
| 425 | const sql = yield* PgClient.PgClient |
| 426 | const cause = yield* sql.withTransaction(Effect.gen(function*() { |
| 427 | yield* Effect.ignore(sql`SELECT 1 / 0`) |
| 428 | })).pipe(Effect.sandbox, Effect.flip) |
| 429 | |
| 430 | assert.isFalse(Cause.hasDies(cause)) |
| 431 | assert.isTrue(Cause.hasFails(cause)) |
| 432 | const error = Cause.squash(cause) |
| 433 | assert.instanceOf(error, SqlError.SqlError) |
| 434 | assert.strictEqual(error.reason._tag, "UnknownError") |
| 435 | assert.strictEqual(error.reason.operation, "commit") |
| 436 | |
| 437 | const rows = yield* sql.withTransaction(sql<{ value: number }>`SELECT 1 AS value`) |
| 438 | assert.deepStrictEqual(rows, [{ value: 1 }]) |
| 439 | })) |
| 440 | } |
| 441 | ) |
| 442 | |
| 443 | it.layer(PgContainer.layerMakeClient, { timeout: "30 seconds" })("PgClient.makeClient", (it) => { |
| 444 | it.effect("connects before executing queries", () => |
| 445 | Effect.gen(function*() { |
| 446 | const sql = yield* PgClient.PgClient |
| 447 | const rows = yield* sql<{ value: number }>`SELECT 1 AS value` |
| 448 | assert.deepStrictEqual(rows, [{ value: 1 }]) |
| 449 | })) |
| 450 | |
| 451 | it.effect("skips prepared statements for unprepared executions only", () => |
| 452 | Effect.gen(function*() { |
| 453 | const sql = yield* PgClient.PgClient |
| 454 | const rows = sql<{ unprepared_row: number }>`SELECT ${1}::int4 AS unprepared_row` |
| 455 | const values = sql`SELECT ${2}::int4 AS unprepared_values` |
| 456 | const preparedStatements = sql<{ statement: string }>` |
| 457 | SELECT statement FROM pg_prepared_statements |
| 458 | WHERE statement IN ( |
| 459 | 'SELECT $1::int4 AS unprepared_row', |
| 460 | 'SELECT $1::int4 AS unprepared_values' |
| 461 | ) |
| 462 | ORDER BY statement |
| 463 | ` |
| 464 | |
| 465 | assert.deepStrictEqual(yield* rows.unprepared, [{ unprepared_row: 1 }]) |
| 466 | assert.deepStrictEqual(yield* values.valuesUnprepared, [[2]]) |
| 467 | assert.deepStrictEqual(yield* preparedStatements, []) |
| 468 | |
| 469 | assert.deepStrictEqual(yield* rows, [{ unprepared_row: 1 }]) |
| 470 | assert.deepStrictEqual(yield* values.values, [[2]]) |
| 471 | assert.deepStrictEqual(yield* preparedStatements, [ |
| 472 | { statement: "SELECT $1::int4 AS unprepared_row" }, |
| 473 | { statement: "SELECT $1::int4 AS unprepared_values" } |
| 474 | ]) |
| 475 | })) |
| 476 | |
| 477 | it.effect("pins the primary connection for streams by default", () => |
| 478 | Effect.gen(function*() { |
| 479 | const sql = yield* PgClient.PgClient |
| 480 | const streamStarted = yield* Deferred.make<void>() |
| 481 | const releaseStream = yield* Deferred.make<void>() |
| 482 | const streamFiber = yield* sql<{ value: number }>`SELECT generate_series(1, 2) AS value`.stream.pipe( |
| 483 | Stream.tap(() => |
| 484 | Effect.andThen( |
| 485 | Deferred.succeed(streamStarted, undefined), |
| 486 | Deferred.await(releaseStream) |
| 487 | ) |
| 488 | ), |
| 489 | Stream.runCollect, |
| 490 | Effect.forkScoped |
| 491 | ) |
| 492 | |
| 493 | yield* Deferred.await(streamStarted) |
| 494 | const rows = yield* sql<{ value: number }>`SELECT 1 AS value`.pipe( |
| 495 | Effect.timeoutOption("100 millis") |
| 496 | ) |
| 497 | yield* Deferred.succeed(releaseStream, undefined) |
| 498 | yield* Fiber.join(streamFiber) |
| 499 | |
| 500 | assert.isTrue(Option.isNone(rows)) |
| 501 | }).pipe(TestClock.withLive)) |
| 502 | |
| 503 | it.effect("serializes transactions on its single connection", () => |
| 504 | Effect.gen(function*() { |
| 505 | const sql = yield* PgClient.PgClient |
| 506 | const firstBodyStarted = yield* Deferred.make<void>() |
| 507 | const releaseFirstBody = yield* Deferred.make<void>() |
| 508 | const secondBodyStarted = yield* Deferred.make<void>() |
| 509 | |
| 510 | const first = yield* sql.withTransaction(Effect.gen(function*() { |
| 511 | yield* Deferred.succeed(firstBodyStarted, undefined) |
| 512 | yield* Deferred.await(releaseFirstBody) |
| 513 | })).pipe(Effect.forkScoped) |
| 514 | yield* Deferred.await(firstBodyStarted) |
| 515 | const second = yield* sql.withTransaction( |
| 516 | Deferred.succeed(secondBodyStarted, undefined) |
| 517 | ).pipe(Effect.forkScoped) |
| 518 | |
| 519 | const overlap = yield* Deferred.await(secondBodyStarted).pipe( |
| 520 | Effect.timeoutOption("100 millis"), |
| 521 | TestClock.withLive |
| 522 | ) |
| 523 | yield* Deferred.succeed(releaseFirstBody, undefined) |
| 524 | yield* Fiber.join(first) |
| 525 | yield* Fiber.join(second) |
| 526 | |
| 527 | assert.isTrue(Option.isNone(overlap)) |
| 528 | })) |
| 529 | |
| 530 | // A transaction pooler moves the session to another server between |
| 531 | // transactions, where the statements prepared on the last one do not exist. |
| 532 | it.effect("ends transactions whose prepared statements went missing", () => |
| 533 | Effect.gen(function*() { |
| 534 | // Its own session, so `DEALLOCATE ALL` cannot affect concurrent tests. |
| 535 | const sql = yield* PgClient.makeClient((yield* PgClient.PgClient).config) |
| 536 | const select = sql<{ value: number }>`SELECT ${1}::int4 AS value` |
| 537 | const assertSqlFailure = (cause: Cause.Cause<unknown>) => { |
| 538 | assert.isFalse(Cause.hasDies(cause)) |
| 539 | const error = Cause.squash(cause) |
| 540 | assert.instanceOf(error, SqlError.SqlError) |
| 541 | assert.propertyVal(error.reason.cause, "code", "26000") |
| 542 | } |
| 543 | // Prepares BEGIN, the body, ROLLBACK and COMMIT. |
| 544 | yield* sql.withTransaction(Effect.andThen(select, Effect.fail("rollback"))).pipe(Effect.flip) |
| 545 | yield* sql.withTransaction(select) |
| 546 | yield* sql`DEALLOCATE ALL`.unprepared |
| 547 | |
| 548 | // The body fails on its lost statement, and ROLLBACK still has to run. |
| 549 | assertSqlFailure(yield* sql.withTransaction(select).pipe(Effect.sandbox, Effect.flip)) |
| 550 | // The body succeeds, but the lost COMMIT never runs. |
| 551 | assertSqlFailure( |
| 552 | yield* sql.withTransaction(sql`SELECT ${2}::int4 AS fresh`).pipe(Effect.sandbox, Effect.flip) |
| 553 | ) |
| 554 | |
| 555 | assert.deepStrictEqual(yield* sql.withTransaction(select), [{ value: 1 }]) |
| 556 | }).pipe(Effect.scoped, Effect.provide(Reactivity.layer))) |
| 557 | }) |
| 558 | |
| 559 | it.layer(PgContainer.layerMakeClientAcquireForStream, { timeout: "30 seconds" })( |
| 560 | "PgClient.makeClient acquireForStream", |
| 561 | (it) => { |
| 562 | it.effect("runs queries while a stream is active", () => |
| 563 | Effect.gen(function*() { |
| 564 | const sql = yield* PgClient.PgClient |
| 565 | const streamStarted = yield* Deferred.make<void>() |
| 566 | const releaseStream = yield* Deferred.make<void>() |
| 567 | const streamFiber = yield* sql<{ value: number }>`SELECT generate_series(1, 2) AS value`.stream.pipe( |
| 568 | Stream.tap(() => |
| 569 | Effect.andThen( |
| 570 | Deferred.succeed(streamStarted, undefined), |
| 571 | Deferred.await(releaseStream) |
| 572 | ) |
| 573 | ), |
| 574 | Stream.runCollect, |
| 575 | Effect.forkScoped |
| 576 | ) |
| 577 | |
| 578 | yield* Deferred.await(streamStarted) |
| 579 | const rows = yield* sql<{ value: number }>`SELECT 1 AS value`.pipe( |
| 580 | Effect.timeoutOrElse({ |
| 581 | duration: "3 seconds", |
| 582 | orElse: () => Effect.fail(new Error("query timed out while stream was active")) |
| 583 | }) |
| 584 | ) |
| 585 | yield* Deferred.succeed(releaseStream, undefined) |
| 586 | yield* Fiber.join(streamFiber) |
| 587 | |
| 588 | assert.deepStrictEqual(rows, [{ value: 1 }]) |
| 589 | }).pipe(TestClock.withLive)) |
| 590 | |
| 591 | it.effect("uses a new session for streams", () => |
| 592 | Effect.gen(function*() { |
| 593 | const sql = yield* PgClient.PgClient |
| 594 | yield* sql`SET application_name = 'sticky-primary'` |
| 595 | |
| 596 | const rows = yield* sql<{ applicationName: string }>` |
| 597 | SELECT current_setting('application_name') AS "applicationName" |
| 598 | `.stream.pipe(Stream.runCollect) |
| 599 | |
| 600 | assert.deepStrictEqual(Array.from(rows), [{ applicationName: "side-default" }]) |
| 601 | })) |
| 602 | } |
| 603 | ) |
| 604 | |
| 605 | it.effect("PgClient.makeClient surfaces transport creation failures", () => |
| 606 | Effect.gen(function*() { |
| 607 | const error = yield* Effect.flip(PgClient.makeClient({ |
| 608 | username: "test", |
| 609 | stream: () => { |
| 610 | throw new Error("connection failed") |
| 611 | } |
| 612 | })) |
| 613 | |
| 614 | assert.strictEqual(error.reason._tag, "ConnectionError") |
| 615 | assert.strictEqual(error.reason.operation, "connect") |
| 616 | }).pipe( |
| 617 | Effect.scoped, |
| 618 | Effect.provide(Reactivity.layer) |
| 619 | )) |
| 620 | |
| 621 | it.layer(PgContainer.layerClientWithTransforms, { timeout: "30 seconds" })("PgClient transforms", (it) => { |
| 622 | it.effect("insert helper", () => |
| 623 | Effect.gen(function*() { |
| 624 | const sql = yield* PgClient.PgClient |
| 625 | const [query, params] = sql`INSERT INTO people ${sql.insert({ firstName: "Tim", age: 10 })}`.compile() |
| 626 | expect(query).toEqual(`INSERT INTO people ("first_name","age") VALUES ($1,$2)`) |
| 627 | expect(params).toEqual(["Tim", 10]) |
| 628 | })) |
| 629 | |
| 630 | it.effect("insert helper withoutTransforms", () => |
| 631 | Effect.gen(function*() { |
| 632 | const sql = (yield* PgClient.PgClient).withoutTransforms() |
| 633 | const [query, params] = sql`INSERT INTO people ${sql.insert({ first_name: "Tim", age: 10 })}`.compile() |
| 634 | expect(query).toEqual(`INSERT INTO people ("first_name","age") VALUES ($1,$2)`) |
| 635 | expect(params).toEqual(["Tim", 10]) |
| 636 | })) |
| 637 | |
| 638 | it.effect("rejects multi-statement queries", () => |
| 639 | Effect.gen(function*() { |
| 640 | const sql = yield* SqlClient.SqlClient |
| 641 | |
| 642 | const error = yield* Effect.flip(sql` |
| 643 | CREATE TABLE test_multi (id TEXT PRIMARY KEY, name TEXT); |
| 644 | SELECT 1; |
| 645 | `) |
| 646 | |
| 647 | assert.strictEqual(error.reason._tag, "SqlSyntaxError") |
| 648 | })) |
| 649 | |
| 650 | it.effect("interruption", () => |
| 651 | Effect.gen(function*() { |
| 652 | const sql = yield* SqlClient.SqlClient |
| 653 | const conn = yield* sql.reserve |
| 654 | yield* conn.executeRaw("select pg_sleep(1000)", []).pipe( |
| 655 | Effect.timeoutOption("50 millis"), |
| 656 | TestClock.withLive |
| 657 | ) |
| 658 | const value = yield* conn.executeValues("select 1", []) |
| 659 | expect(value).toEqual([[1]]) |
| 660 | })) |
| 661 | |
| 662 | it.effect("retains the supplied config", () => |
| 663 | Effect.gen(function*() { |
| 664 | const sql = yield* PgClient.PgClient |
| 665 | |
| 666 | assert.isDefined(sql.config.url) |
| 667 | expect(sql.config.transformResultNames).toEqual(String.snakeToCamel) |
| 668 | expect(sql.config.transformQueryNames).toEqual(String.camelToSnake) |
| 669 | })) |
| 670 | }) |
| 671 | |
| 672 | // Each listener uses one of two pool connections. |
| 673 | it.layer(PgContainer.layerClientForListen, { timeout: "30 seconds", concurrent: false })("PgClient listen", (it) => { |
| 674 | it.effect("keeps queries available while a listener reserves one connection", () => |
| 675 | Effect.gen(function*() { |
| 676 | const sql = yield* PgClient.PgClient |
| 677 | const channel = "pool_connection_listen" |
| 678 | |
| 679 | const payloads = yield* sql.listen(channel) |
| 680 | |
| 681 | const rows = yield* sql<{ value: number }>`SELECT 1 as value`.pipe( |
| 682 | Effect.timeoutOrElse({ |
| 683 | duration: "3 seconds", |
| 684 | orElse: () => Effect.fail(new Error("query timed out while listener was active")) |
| 685 | }) |
| 686 | ) |
| 687 | expect(rows).toEqual([{ value: 1 }]) |
| 688 | |
| 689 | yield* sql.notify(channel, "payload") |
| 690 | const payload = yield* Queue.take(payloads).pipe( |
| 691 | Effect.timeoutOrElse({ |
| 692 | duration: "3 seconds", |
| 693 | orElse: () => Effect.fail(new Error("listener did not receive notification in time")) |
| 694 | }) |
| 695 | ) |
| 696 | expect(payload.payload).toEqual("payload") |
| 697 | }).pipe(TestClock.withLive), { timeout: 20_000 }) |
| 698 | |
| 699 | it.effect("notify sends payload", () => |
| 700 | Effect.gen(function*() { |
| 701 | const sql = yield* PgClient.PgClient |
| 702 | const channel = "pool_connection_notify" |
| 703 | |
| 704 | const payloads = yield* sql.listen(channel) |
| 705 | yield* sql.notify(channel, "payload") |
| 706 | |
| 707 | const payload = yield* Queue.take(payloads).pipe( |
| 708 | Effect.timeoutOrElse({ |
| 709 | duration: "3 seconds", |
| 710 | orElse: () => Effect.fail(new Error("listener did not receive notification in time")) |
| 711 | }) |
| 712 | ) |
| 713 | expect(payload.payload).toEqual("payload") |
| 714 | }).pipe(TestClock.withLive), { timeout: 20_000 }) |
| 715 | |
| 716 | it.effect("retries a failed listener and receives notifications on a new connection", () => |
| 717 | Effect.gen(function*() { |
| 718 | const sql = yield* PgClient.PgClient |
| 719 | const channel = "retry_listener" |
| 720 | const registered = yield* Queue.unbounded<void>() |
| 721 | const consumer = yield* Stream.unwrap(Effect.gen(function*() { |
| 722 | const notifications = yield* sql.listen(channel) |
| 723 | yield* Queue.offer(registered, undefined) |
| 724 | return Stream.fromQueue(notifications) |
| 725 | })).pipe( |
| 726 | Stream.retry(Schedule.recurs(1)), |
| 727 | Stream.runHead, |
| 728 | Effect.forkScoped |
| 729 | ) |
| 730 | |
| 731 | yield* Queue.take(registered) |
| 732 | const [listener] = yield* sql<{ pid: number }>` |
| 733 | SELECT pid FROM pg_stat_activity WHERE query = ${`LISTEN "${channel}"`} |
| 734 | ` |
| 735 | assert.isDefined(listener) |
| 736 | yield* sql`SELECT pg_terminate_backend(${listener.pid})` |
| 737 | |
| 738 | // Wait for registration; PostgreSQL does not replay missed notifications. |
| 739 | yield* Queue.take(registered) |
| 740 | const [replacement] = yield* sql<{ pid: number }>` |
| 741 | SELECT pid FROM pg_stat_activity |
| 742 | WHERE query = ${`LISTEN "${channel}"`} AND pid <> ${listener.pid} |
| 743 | ` |
| 744 | assert.isDefined(replacement) |
| 745 | yield* sql.notify(channel, "after reconnect") |
| 746 | const notification = Option.getOrThrow(yield* Fiber.join(consumer)) |
| 747 | assert.strictEqual(notification.channel, channel) |
| 748 | assert.strictEqual(notification.payload, "after reconnect") |
| 749 | }), { timeout: 20_000 }) |
| 750 | |
| 751 | it.effect("listen rejects channel names longer than 63 UTF-8 bytes", () => |
| 752 | Effect.gen(function*() { |
| 753 | const sql = yield* PgClient.PgClient |
| 754 | const error = yield* Effect.flip(sql.listen("é".repeat(32))) |
| 755 | |
| 756 | assert.strictEqual(error.message, "PostgreSQL channel names must not exceed 63 UTF-8 bytes") |
| 757 | assert.strictEqual(error.reason.operation, "listen") |
| 758 | })) |
| 759 | |
| 760 | it.effect("notify rejects channel names longer than 63 UTF-8 bytes", () => |
| 761 | Effect.gen(function*() { |
| 762 | const sql = yield* PgClient.PgClient |
| 763 | const error = yield* Effect.flip(sql.notify("é".repeat(32), "payload")) |
| 764 | |
| 765 | assert.strictEqual(error.message, "PostgreSQL channel names must not exceed 63 UTF-8 bytes") |
| 766 | assert.strictEqual(error.reason.operation, "notify") |
| 767 | })) |
| 768 | }) |
| 769 | |
| 770 | const RequestId = Context.Reference<string>("test/RequestId", { defaultValue: () => "none" }) |
| 771 | |
| 772 | class Prefix extends Context.Service<Prefix, string>()("test/Prefix") {} |
| 773 | |
| 774 | it.layer(PgContainer.layer, { timeout: "30 seconds" })("PgClient onAcquire", (it) => { |
| 775 | it.effect("runs once per acquisition with construction services in the consuming fiber", () => |
| 776 | Effect.gen(function*() { |
| 777 | const container = yield* PgContainer |
| 778 | const calls: Array<string> = [] |
| 779 | const context = yield* Layer.build( |
| 780 | PgClient.layer({ |
| 781 | url: Redacted.make(container.getConnectionUri()), |
| 782 | onAcquire: Effect.gen(function*() { |
| 783 | calls.push(`${yield* Prefix}:${yield* RequestId}`) |
| 784 | }) |
| 785 | }).pipe(Layer.provide(Layer.succeed(Prefix, "pool"))) |
| 786 | ) |
| 787 | const sql = Context.get(context, PgClient.PgClient) |
| 788 | |
| 789 | yield* sql`SELECT 1`.pipe(Effect.provideService(RequestId, "statement")) |
| 790 | yield* sql.withTransaction(Effect.andThen(sql`SELECT 1`, sql`SELECT 2`)).pipe( |
| 791 | Effect.provideService(RequestId, "transaction") |
| 792 | ) |
| 793 | |
| 794 | assert.deepStrictEqual(calls, ["pool:statement", "pool:transaction"]) |
| 795 | }).pipe(Effect.scoped)) |
| 796 | |
| 797 | it.effect("closes the hook's scope after each statement", () => |
| 798 | Effect.gen(function*() { |
| 799 | const container = yield* PgContainer |
| 800 | let finalized = 0 |
| 801 | const sql = yield* PgClient.make({ |
| 802 | url: Redacted.make(container.getConnectionUri()), |
| 803 | onAcquire: Effect.addFinalizer(() => |
| 804 | Effect.sync(() => { |
| 805 | finalized++ |
| 806 | }) |
| 807 | ) |
| 808 | }) |
| 809 | |
| 810 | yield* sql`SELECT 1` |
| 811 | yield* sql`SELECT 1` |
| 812 | |
| 813 | assert.strictEqual(finalized, 2) |
| 814 | }).pipe(Effect.scoped, Effect.provide(Reactivity.layer))) |
| 815 | }) |