diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 29600277132..0b5a64bffd6 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -2119,6 +2119,26 @@ register before writing, or they can remain unseen until the next startup or another notification. Tests should verify both the producer and its outer transaction boundary. +## Relational queries inside transactions + +Drizzle builds one relational query builder for every schema table when it +creates a database object, and it creates one for each transaction and each +savepoint. With the Paperclip schema that is about 100 KB per transaction. +`createDb` therefore opens transactions through a second Drizzle client on the +same postgres.js client, created without the schema, and builds `tx.query` the +first time a transaction reads it (`packages/db/src/lazy-transaction-queries.ts`). +`db.query`, `tx.query`, and `tx._` keep their contents. `BEGIN`, `SAVEPOINT`, +commit, rollback, and connection reservation remain Drizzle's and the driver's. + +Measure the cost of a transaction and a savepoint with the command below. It +needs Node.js 25 or later, because Node.js 24 has no V8 allocation counter, and +it stops with that message on an older runtime: + +```sh +cd packages/db +TSX_DISABLE_CACHE=1 node --expose-gc --import tsx scripts/benchmark-transaction-allocation.ts +``` + ### Installed skill packages `company_skill_repository_snapshots` retains its identity and company/content-hash diff --git a/packages/db/scripts/benchmark-transaction-allocation.ts b/packages/db/scripts/benchmark-transaction-allocation.ts new file mode 100644 index 00000000000..4b40f38b44e --- /dev/null +++ b/packages/db/scripts/benchmark-transaction-allocation.ts @@ -0,0 +1,161 @@ +// What one transaction or savepoint costs on the Paperclip database client, +// measured against a local PostgreSQL. +// +// cd packages/db +// TSX_DISABLE_CACHE=1 node --expose-gc --import tsx scripts/benchmark-transaction-allocation.ts [iterations] [passes] +// +// Three clients run the same scenarios: `createDb`, Drizzle given the schema +// directly (one relational query builder per table for every transaction, which +// is what `createDb` did before transactions built `tx.query` on first read), +// and Drizzle without a schema (the floor). +// +// Each scenario runs `passes` times for `iterations` iterations, with a forced +// collection before every pass, and reports the median pass. Allocation is +// V8's total_allocated_bytes counter, CPU is process.cpuUsage(), and a +// collection counts only when it starts inside the measured window. The +// allocation profile attributes an empty transaction's bytes to named frames. +// TSX_DISABLE_CACHE keeps tsx from scanning its shared cache while passes run. +// +// Needs Node.js 25 or later: Node.js 24 has no total_allocated_bytes counter, +// and the script stops with that message instead of printing empty numbers. +import inspector from "node:inspector/promises"; +import { cpus, loadavg } from "node:os"; +import { PerformanceObserver, performance } from "node:perf_hooks"; +import v8 from "node:v8"; +import { sql } from "drizzle-orm"; +import { drizzle } from "drizzle-orm/postgres-js"; +import postgres from "postgres"; +import { createDb } from "../src/client.js"; +import * as schema from "../src/schema/index.js"; +import { startEmbeddedPostgresTestDatabase } from "../src/test-embedded-postgres.js"; + +const iterations = Number(process.argv[2] ?? 3000); +const passes = Number(process.argv[3] ?? 5); +if (!Number.isInteger(iterations) || iterations < 1 || !Number.isInteger(passes) || passes < 1) { + throw new Error("Usage: benchmark-transaction-allocation.ts [iterations] [passes]"); +} +const collect = (globalThis as { gc?: () => void }).gc; +if (!collect) throw new Error("Run node with --expose-gc"); + +type Sample = { allocatedBytes: number; cpuMicros: number; wallMicros: number; collections: number; collectionMs: number }; +const allocated = () => (v8.getHeapStatistics() as unknown as { total_allocated_bytes: number }).total_allocated_bytes; +if (typeof allocated() !== "number") { + throw new Error(`This benchmark needs Node.js 25 or later; ${process.version} has no v8 total_allocated_bytes counter`); +} +const median = (values: number[]) => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)]!; +const settle = () => new Promise(resolve => setImmediate(resolve)); + +const collectionEntries: { start: number; duration: number }[] = []; +const observer = new PerformanceObserver(list => { + for (const entry of list.getEntries()) collectionEntries.push({ start: entry.startTime, duration: entry.duration }); +}); +observer.observe({ entryTypes: ["gc"] }); + +async function pass(action: () => Promise | unknown): Promise { + collect!(); collect!(); + await settle(); + const startedAt = performance.now(), cpu = process.cpuUsage(), before = allocated(); + for (let index = 0; index < iterations; index += 1) await action(); + const allocatedBytes = allocated() - before, used = process.cpuUsage(cpu), endedAt = performance.now(); + await settle(); await settle(); + const inWindow = collectionEntries.filter(entry => entry.start >= startedAt && entry.start < endedAt); + return { + allocatedBytes: allocatedBytes / iterations, + cpuMicros: (used.user + used.system) / iterations, + wallMicros: (endedAt - startedAt) * 1000 / iterations, + collections: inWindow.length * 1000 / iterations, + collectionMs: inWindow.reduce((sum, entry) => sum + entry.duration, 0) * 1000 / iterations, + }; +} + +async function measure(client: string, scenario: string, action: () => Promise | unknown) { + for (let index = 0; index < 300; index += 1) await action(); + const samples: Sample[] = []; + for (let index = 0; index < passes; index += 1) samples.push(await pass(action)); + const result = { + kind: "scenario", client, scenario, + allocatedBytesPerIteration: Math.round(median(samples.map(sample => sample.allocatedBytes))), + cpuMicrosPerIteration: Number(median(samples.map(sample => sample.cpuMicros)).toFixed(1)), + cpuMicrosMin: Number(Math.min(...samples.map(sample => sample.cpuMicros)).toFixed(1)), + wallMicrosPerIteration: Number(median(samples.map(sample => sample.wallMicros)).toFixed(1)), + collectionsPer1000: Number(median(samples.map(sample => sample.collections)).toFixed(1)), + collectionMsPer1000: Number(median(samples.map(sample => sample.collectionMs)).toFixed(2)), + }; + console.log(JSON.stringify(result)); + return result; +} + +type AnyDb = { + execute(query: unknown): Promise; + transaction(callback: (tx: AnyDb) => Promise, config?: unknown): Promise; +}; + +async function scenarios(client: string, db: AnyDb) { + const statement = sql`select 1`; + await measure(client, "statement outside a transaction", () => db.execute(statement)); + await measure(client, "empty transaction", () => db.transaction(async () => {})); + await measure(client, "transaction with one statement", () => db.transaction(async tx => { await tx.execute(statement); })); + await measure(client, "transaction with an empty savepoint", () => db.transaction(async tx => { await tx.transaction(async () => {}); })); + await measure(client, "transaction with a savepoint of one statement", + () => db.transaction(async tx => { await tx.transaction(async inner => { await inner.execute(statement); }); })); +} + +type Node = { callFrame: { functionName: string; url: string; lineNumber: number }; selfSize: number; children?: Node[] }; + +async function allocationProfile(client: string, db: AnyDb, count: number) { + for (let index = 0; index < 300; index += 1) await db.transaction(async () => {}); + collect!(); collect!(); + const session = new inspector.Session(); + session.connect(); + await session.post("HeapProfiler.enable"); + await session.post("HeapProfiler.startSampling", { + samplingInterval: 256, includeObjectsCollectedByMajorGC: true, includeObjectsCollectedByMinorGC: true, + } as never); + for (let index = 0; index < count; index += 1) await db.transaction(async () => {}); + const { profile } = await session.post("HeapProfiler.stopSampling") as unknown as { profile: { head: Node } }; + session.disconnect(); + const self = new Map(), inclusive = new Map(); + let total = 0; + const label = (node: Node) => { + const file = node.callFrame.url.replace(/^.*node_modules\//, "").replace(/^file:\/\/.*\/packages\//, "packages/"); + return `${node.callFrame.functionName || "(anonymous)"} ${file}:${node.callFrame.lineNumber + 1}`; + }; + const walk = (node: Node, ancestors: string[]): number => { + const name = label(node); + let size = node.selfSize; + for (const child of node.children ?? []) size += walk(child, [...ancestors, name]); + self.set(name, (self.get(name) ?? 0) + node.selfSize); + // Count a frame once per stack so recursion does not double its share. + if (!ancestors.includes(name)) inclusive.set(name, (inclusive.get(name) ?? 0) + size); + total += node.selfSize; + return size; + }; + walk(profile.head, []); + const top = (map: Map, limit: number) => [...map.entries()].sort((a, b) => b[1] - a[1]).slice(0, limit) + .map(([frame, bytes]) => ({ frame, bytesPerTransaction: Math.round(bytes / count), share: Number((bytes / total).toFixed(3)) })); + console.log(JSON.stringify({ kind: "allocation-profile", client, scenario: "empty transaction", transactions: count, + sampledBytesPerTransaction: Math.round(total / count), self: top(self, 6), inclusive: top(inclusive, 10) })); +} + +const database = await startEmbeddedPostgresTestDatabase("paperclip-db-transaction-allocation-"); +// These two pools are not registered with createDb, so database.cleanup() does +// not end them. End them before PostgreSQL stops, also when a scenario throws. +const eagerSql = postgres(database.connectionString, { max: 10, onnotice: () => {} }); +const bareSql = postgres(database.connectionString, { max: 10, onnotice: () => {} }); +try { + const db = createDb(database.connectionString) as unknown as AnyDb & { _: { schema: Record } }; + const eager = drizzle(eagerSql, { schema }) as unknown as AnyDb; + const bare = drizzle(bareSql) as unknown as AnyDb; + console.log(JSON.stringify({ kind: "host", node: process.version, logicalCpus: cpus().length, loadavg: loadavg().map(value => Number(value.toFixed(1))), + iterations, passes, schemaTables: Object.keys(db._.schema).length, + boundary: "three clients on one local PostgreSQL; allocation = V8 total_allocated_bytes; CPU = process user+system; median pass" })); + await scenarios("paperclip createDb", db); + await scenarios("drizzle with the schema", eager); + await scenarios("drizzle without a schema", bare); + await allocationProfile("paperclip createDb", db, Math.min(iterations, 2000)); + await allocationProfile("drizzle with the schema", eager, Math.min(iterations, 2000)); +} finally { + observer.disconnect(); + await Promise.allSettled([eagerSql.end({ timeout: 1 }), bareSql.end({ timeout: 1 })]); + await database.cleanup(); +} diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 6e6df8060c9..aa4f0c9fd06 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -1,11 +1,11 @@ import { createHash } from "node:crypto"; -import { drizzle as drizzlePg } from "drizzle-orm/postgres-js"; import { readFile, readdir } from "node:fs/promises"; import { fileURLToPath } from "node:url"; import postgres from "postgres"; import { installDatabaseWorkSignals } from "./work-signals.js"; import { installDatabaseResponseCapture } from "./response-capture.js"; import { installPreparedQueries } from "./prepared-queries.js"; +import { drizzleWithLazyTransactionQueries } from "./lazy-transaction-queries.js"; import * as schema from "./schema/index.js"; const MIGRATIONS_FOLDER = fileURLToPath(new URL("./migrations", import.meta.url)); @@ -392,7 +392,7 @@ function createDbClient(url: string, resolved: DatabaseClientOptions, owner?: ob // postgres.js calls that error "write CONNECTION_CLOSED" too, so the // message cannot establish that replay is safe. Leave retries to callers // that know the complete operation is idempotent. - const db = installDatabaseWorkSignals(drizzlePg(sql, { schema }), owner); + const db = installDatabaseWorkSignals(drizzleWithLazyTransactionQueries(sql, schema), owner); installDatabaseResponseCapture(db, schema); dedicatedDbFactories.set(db, () => createDbClient(url, { ...resolved, maxConnections: 1, applicationName: "paperclip-workspace-finalization-lock", diff --git a/packages/db/src/lazy-transaction-queries.test.ts b/packages/db/src/lazy-transaction-queries.test.ts new file mode 100644 index 00000000000..2cefdf6c8a6 --- /dev/null +++ b/packages/db/src/lazy-transaction-queries.test.ts @@ -0,0 +1,369 @@ +import v8 from "node:v8"; +import { and, eq, sql, TransactionRollbackError } from "drizzle-orm"; +import { drizzle } from "drizzle-orm/postgres-js"; +import postgres from "postgres"; +import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; +import { createDb, type Db } from "./client.js"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "./response-capture.js"; +import { announcementDismissals, announcementPublications } from "./schema/index.js"; +import { + EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, + getEmbeddedPostgresTestSupport, + startEmbeddedPostgresTestDatabase, +} from "./test-embedded-postgres.js"; +import { + databaseWorkPending, databaseWorkScopeKey, reconcileDatabaseWork, signalDatabaseWork, subscribeDatabaseWork, +} from "./work-signals.js"; + +type Tx = Parameters[0]>[0]; + +const support = await getEmbeddedPostgresTestSupport(); +const describeEmbeddedPostgres = support.supported ? describe : describe.skip; +const allocatedBytes = () => (v8.getHeapStatistics() as { total_allocated_bytes?: number }).total_allocated_bytes; + +/** Relational query builders a database object holds without `query` having been read. */ +function builtQueryBuilders(connection: object): number { + const query = Object.getOwnPropertyDescriptor(connection, "query")?.value as object | undefined; + return query ? Object.keys(query).length : 0; +} + +const publication = (tx: Pick, announcementId: string) => + tx.insert(announcementPublications).values({ announcementId }); +const publicationIds = async (connection: Pick) => + (await connection.select().from(announcementPublications)).map(row => row.announcementId).sort(); +const backendPid = async (connection: Pick) => + (await connection.execute<{ pid: number }>(sql`select pg_backend_pid() as pid`))[0]!.pid; + +describeEmbeddedPostgres("transactions on the Paperclip database client", () => { + let database: Awaited>; + let db: Db; + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("paperclip-db-lazy-transaction-queries-"); + db = createDb(database.connectionString); + }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); + afterEach(async () => { + await db.delete(announcementDismissals); + await db.delete(announcementPublications); + }); + afterAll(async () => { await database?.cleanup(); }); + + describe("relational query builders", () => { + it("builds none for a transaction or savepoint that never reads tx.query", async () => { + const schemaTables = Object.keys(db.query).length; + expect(schemaTables).toBeGreaterThan(100); + expect(builtQueryBuilders(db)).toBe(schemaTables); + const built = await db.transaction(async (tx) => { + await publication(tx, "unread"); + const outer = builtQueryBuilders(tx); + const savepoint = await tx.transaction(async (nested) => { + await nested.select().from(announcementPublications); + return builtQueryBuilders(nested); + }); + return { outer, savepoint, outerAfterSavepoint: builtQueryBuilders(tx) }; + }); + expect(built).toEqual({ outer: 0, savepoint: 0, outerAfterSavepoint: 0 }); + }); + + it.skipIf(allocatedBytes() === undefined)("allocates the same for an empty transaction as a client without the schema", async () => { + const bareClient = postgres(database.connectionString, { max: 1, onnotice: () => {} }); + try { + const bare = drizzle(bareClient); + const perTransaction = async (connection: { transaction(callback: () => Promise): Promise }) => { + for (let index = 0; index < 100; index += 1) await connection.transaction(async () => {}); + const before = allocatedBytes()!; + for (let index = 0; index < 300; index += 1) await connection.transaction(async () => {}); + return (allocatedBytes()! - before) / 300; + }; + const withoutSchema = await perTransaction(bare); + const withSchema = await perTransaction(db); + // Eager builders cost about 100 KB per transaction for 321 tables. + expect(withSchema - withoutSchema).toBeLessThan(16 * 1024); + } finally { + await bareClient.end({ timeout: 1 }); + } + }); + + it("gives tx.query one builder per schema table, the same object on every read", async () => { + await db.transaction(async (tx) => { + const query = tx.query; + expect(tx.query).toBe(query); + expect(Object.keys(query)).toEqual(Object.keys(db.query)); + expect(builtQueryBuilders(tx)).toBe(Object.keys(db.query).length); + expect(query.announcementPublications.constructor).toBe(db.query.announcementPublications.constructor); + expect(query.announcementPublications).not.toBe(db.query.announcementPublications); + expect(Object.keys(tx)).toContain("query"); + expect(tx._.fullSchema).toBe(db._.fullSchema); + expect(tx._.schema).toBe(db._.schema); + expect(tx._.tableNamesMap).toBe(db._.tableNamesMap); + await tx.transaction(async (nested) => { + expect(nested.query).not.toBe(query); + expect(Object.keys(nested.query)).toEqual(Object.keys(db.query)); + expect(nested._.fullSchema).toBe(db._.fullSchema); + }); + }); + }); + + it("reads tx.query through the transaction, as the announcement and decision-training services do", async () => { + await db.transaction(async (tx) => { + await publication(tx, "in-transaction"); + await tx.insert(announcementDismissals).values({ userId: "user-1", announcementId: "in-transaction" }); + const known = await tx.query.announcementPublications.findFirst({ + where: eq(announcementPublications.announcementId, "in-transaction"), + }); + expect(known).toEqual({ announcementId: "in-transaction" }); + const dismissal = await tx.query.announcementDismissals.findFirst({ + where: and(eq(announcementDismissals.userId, "user-1"), eq(announcementDismissals.announcementId, "in-transaction")), + }); + expect(dismissal).toMatchObject({ userId: "user-1", announcementId: "in-transaction" }); + expect(dismissal!.dismissedAt).toBeInstanceOf(Date); + expect(await tx.query.announcementPublications.findFirst({ + where: eq(announcementPublications.announcementId, "missing"), + })).toBeUndefined(); + expect(await tx.query.announcementDismissals.findMany({ columns: { userId: true } })).toEqual([{ userId: "user-1" }]); + // Another connection must not see the uncommitted rows the transaction's own query read. + expect(await db.query.announcementPublications.findFirst({ + where: eq(announcementPublications.announcementId, "in-transaction"), + })).toBeUndefined(); + }); + expect(await db.query.announcementPublications.findFirst({ + where: eq(announcementPublications.announcementId, "in-transaction"), columns: { announcementId: true }, + })).toEqual({ announcementId: "in-transaction" }); + }); + + it("reads tx.query inside a savepoint and follows its rollback", async () => { + await db.transaction(async (tx) => { + await publication(tx, "outer"); + await expect(tx.transaction(async (nested) => { + await publication(nested, "savepoint"); + expect((await nested.query.announcementPublications.findMany()).map(row => row.announcementId).sort()) + .toEqual(["outer", "savepoint"]); + throw new Error("undo the savepoint"); + })).rejects.toThrow("undo the savepoint"); + expect(await tx.query.announcementPublications.findMany()).toEqual([{ announcementId: "outer" }]); + }); + expect(await db.query.announcementPublications.findMany()).toEqual([{ announcementId: "outer" }]); + }); + }); + + describe("instrumentation of transactions", () => { + const assignedXid = async (connection: Pick) => + (await connection.execute<{ xid: string | null }>(sql`select pg_current_xact_id_if_assigned()::text as xid`))[0]!.xid; + + it("registers each transaction and savepoint with the client's work signals", async () => { + const events: string[] = []; + const unsubscribe = subscribeDatabaseWork(db, "lazy-transaction-queries", event => events.push(event)); + try { + await db.transaction(async (tx) => { + expect(databaseWorkScopeKey(tx)).toBe(databaseWorkScopeKey(db)); + expect(await assignedXid(tx)).toBeNull(); + await tx.transaction(async (nested) => { + expect(databaseWorkScopeKey(nested)).toBe(databaseWorkScopeKey(db)); + await signalDatabaseWork(nested, "lazy-transaction-queries"); + // The registration asked for the transaction ID on this transaction's connection. + expect(await assignedXid(nested)).not.toBeNull(); + await publication(nested, "signalled"); + }); + expect(events).toEqual(["intent"]); + expect(databaseWorkPending(db, "lazy-transaction-queries")).toBe(true); + expect(await tx.query.announcementPublications.findMany()).toEqual([{ announcementId: "signalled" }]); + // A released savepoint and a relational read settle nothing before the outer commit. + expect(events).toEqual(["intent"]); + }); + expect(events).toEqual(["intent", "settled"]); + expect(databaseWorkPending(db, "lazy-transaction-queries")).toBe(false); + + await expect(db.transaction(async (tx) => { + await signalDatabaseWork(tx, "lazy-transaction-queries"); + await publication(tx, "rolled-back"); + throw new Error("rollback"); + })).rejects.toThrow("rollback"); + expect(events).toEqual(["intent", "settled", "intent", "settled"]); + await reconcileDatabaseWork(db, "lazy-transaction-queries"); + expect(databaseWorkPending(db, "lazy-transaction-queries")).toBe(false); + expect(await publicationIds(db)).toEqual(["signalled"]); + await expect(signalDatabaseWork(db, "lazy-transaction-queries")).rejects.toThrow("inside a transaction"); + } finally { unsubscribe(); } + }); + + it("response capture counts every statement of a transaction, a savepoint and tx.query", async () => { + const events: Array> = []; + const now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + const captured = createDb(database.connectionString, { maxConnections: 2 }); + try { + installDatabaseResponseCapture(captured, { announcementPublications, announcementDismissals }, capture); + await captured.transaction(async (tx: Tx) => { + await publication(tx, "captured"); + await tx.select().from(announcementPublications); + await tx.transaction(async (nested: Tx) => { + await nested.update(announcementPublications).set({ announcementId: "captured-renamed" }) + .where(eq(announcementPublications.announcementId, "captured")); + await nested.query.announcementPublications.findFirst({ + where: eq(announcementPublications.announcementId, "captured-renamed"), + }); + await nested.delete(announcementDismissals); + }); + await tx.query.announcementDismissals.findMany(); + }); + capture.flush(); + expect(events.find(event => event.event === "paperclip.db_response_capture.summary.v2")) + .toMatchObject({ startedQueries: 6, completedQueries: 6, inFlightAtEnd: 0 }); + const calls: Record = {}; + for (const event of events.filter(entry => entry.event === "paperclip.db_response_capture.entry.v2")) { + const key = `${String(event.operation)} ${String(event.table)}`; + calls[key] = (calls[key] ?? 0) + Number(event.calls); + } + expect(calls).toEqual({ + "insert announcement_publications": 1, + "select announcement_publications": 2, + "update announcement_publications": 1, + "delete announcement_dismissals": 1, + "select announcement_dismissals": 1, + }); + } finally { + capture.flush(); + await captured.$client.end({ timeout: 1 }); + } + }); + }); + + describe("transaction semantics", () => { + it("commits and returns the callback's value", async () => { + const result = await db.transaction(async (tx) => { + await publication(tx, "committed"); + const [updated] = await tx.update(announcementPublications).set({ announcementId: "renamed" }) + .where(eq(announcementPublications.announcementId, "committed")).returning(); + await publication(tx, "deleted"); + await tx.delete(announcementPublications).where(eq(announcementPublications.announcementId, "deleted")); + return updated; + }); + expect(result).toEqual({ announcementId: "renamed" }); + expect(await publicationIds(db)).toEqual(["renamed"]); + }); + + it("rolls back and rejects with the thrown error", async () => { + const failure = new Error("abort"); + await expect(db.transaction(async (tx) => { + await publication(tx, "discarded"); + throw failure; + })).rejects.toBe(failure); + await expect(db.transaction(async (tx) => { + await publication(tx, "discarded"); + tx.rollback(); + })).rejects.toBeInstanceOf(TransactionRollbackError); + await expect(db.transaction(async (tx) => { + await publication(tx, "duplicate"); + await publication(tx, "duplicate"); + })).rejects.toMatchObject({ cause: { code: "23505" } }); + expect(await publicationIds(db)).toEqual([]); + }); + + it("keeps the outer transaction usable after a savepoint rolls back", async () => { + await db.transaction(async (tx) => { + await publication(tx, "before"); + await expect(tx.transaction(async (nested) => { + await publication(nested, "undone"); + await publication(nested, "undone"); + })).rejects.toMatchObject({ cause: { code: "23505" } }); + await expect(tx.transaction(async (nested) => { + await publication(nested, "undone"); + nested.rollback(); + })).rejects.toBeInstanceOf(TransactionRollbackError); + expect(await publicationIds(tx)).toEqual(["before"]); + await tx.transaction(async (nested) => { + await publication(nested, "released"); + await nested.transaction(async (inner) => { await publication(inner, "released-inner"); }); + await expect(nested.transaction(async (inner) => { + await publication(inner, "undone-inner"); + throw new Error("inner"); + })).rejects.toThrow("inner"); + }); + await publication(tx, "after"); + }); + expect(await publicationIds(db)).toEqual(["after", "before", "released", "released-inner"]); + }); + + it("discards a released savepoint when the outer transaction rolls back", async () => { + await expect(db.transaction(async (tx) => { + await tx.transaction(async (nested) => { await publication(nested, "released"); }); + expect(await publicationIds(tx)).toEqual(["released"]); + throw new Error("outer"); + })).rejects.toThrow("outer"); + expect(await publicationIds(db)).toEqual([]); + }); + + it("applies the isolation level and access mode", async () => { + const settings = await db.transaction(async (tx) => { + const [isolation] = await tx.execute<{ transaction_isolation: string }>(sql`show transaction_isolation`); + const [readOnly] = await tx.execute<{ transaction_read_only: string }>(sql`show transaction_read_only`); + return { ...isolation, ...readOnly }; + }, { isolationLevel: "serializable", accessMode: "read only" }); + expect(settings).toEqual({ transaction_isolation: "serializable", transaction_read_only: "on" }); + await expect(db.transaction(async (tx) => { await publication(tx, "read-only"); }, { accessMode: "read only" })) + .rejects.toMatchObject({ cause: { code: "25006" } }); + const [isolation] = await db.transaction( + async (tx) => tx.execute<{ transaction_isolation: string }>(sql`show transaction_isolation`)); + expect(isolation).toEqual({ transaction_isolation: "read committed" }); + }); + + it("runs concurrent transactions on separate reserved connections and releases them", async () => { + const pooled = createDb(database.connectionString, { maxConnections: 3 }); + let open = 0, mostOpen = 0; + const pids = new Set(); + const run = (index: number) => pooled.transaction(async (tx: Tx) => { + open += 1; mostOpen = Math.max(mostOpen, open); + try { + const pid = await backendPid(tx); + pids.add(pid); + await publication(tx, `concurrent-${index}`); + await tx.execute(sql`select pg_sleep(0.02)`); + // Uncommitted rows of the other open transactions are invisible here. + expect((await publicationIds(tx)).filter(id => id !== `concurrent-${index}` && Number(id.split("-")[1]) % 2 === 1)).toEqual([]); + expect(await tx.transaction(async (nested: Tx) => backendPid(nested))).toBe(pid); + expect(await backendPid(tx)).toBe(pid); + if (index % 2 === 1) throw new Error(`abort ${index}`); + return index; + } finally { open -= 1; } + }); + const settled = await Promise.allSettled(Array.from({ length: 12 }, (_, index) => run(index))); + expect(settled.map(result => result.status === "fulfilled" ? result.value : (result.reason as Error).message)) + .toEqual(Array.from({ length: 12 }, (_, index) => index % 2 === 1 ? `abort ${index}` : index)); + expect(mostOpen).toBeGreaterThan(1); + expect(mostOpen).toBeLessThanOrEqual(3); + expect(pids.size).toBeLessThanOrEqual(3); + expect(await publicationIds(pooled)).toEqual([0, 10, 2, 4, 6, 8].map(index => `concurrent-${index}`)); + await pooled.$client.end({ timeout: 1 }); + }); + + it("returns the only connection to the pool after a commit, a rollback and a failed savepoint", async () => { + const single = createDb(database.connectionString, { maxConnections: 1 }); + const pid = await backendPid(single); + await single.transaction(async (tx: Tx) => { await publication(tx, "single"); }); + await expect(single.transaction(async (tx: Tx) => { + await expect(tx.transaction(async () => { throw new Error("savepoint"); })).rejects.toThrow("savepoint"); + throw new Error("outer"); + })).rejects.toThrow("outer"); + expect(await single.transaction(async (tx: Tx) => backendPid(tx))).toBe(pid); + expect(await publicationIds(single)).toEqual(["single"]); + await single.$client.end({ timeout: 1 }); + }); + + it("behaves the same with prepared statements enabled", async () => { + const prepared = createDb(database.connectionString, { prepare: true, maxConnections: 2 }); + await prepared.transaction(async (tx: Tx) => { + await publication(tx, "prepared"); + await expect(tx.transaction(async (nested: Tx) => { + await publication(nested, "prepared-undone"); + expect(await nested.query.announcementPublications.findFirst({ + where: eq(announcementPublications.announcementId, "prepared-undone"), + })).toEqual({ announcementId: "prepared-undone" }); + throw new Error("undo"); + })).rejects.toThrow("undo"); + expect(builtQueryBuilders(tx)).toBe(0); + }); + expect(await prepared.query.announcementPublications.findMany()).toEqual([{ announcementId: "prepared" }]); + await prepared.$client.end({ timeout: 1 }); + }); + }); +}); diff --git a/packages/db/src/lazy-transaction-queries.ts b/packages/db/src/lazy-transaction-queries.ts new file mode 100644 index 00000000000..e153ca6452b --- /dev/null +++ b/packages/db/src/lazy-transaction-queries.ts @@ -0,0 +1,74 @@ +import { PgDialect, type PgSession, type PgTable } from "drizzle-orm/pg-core"; +import { RelationalQueryBuilder } from "drizzle-orm/pg-core/query-builders/query"; +import { drizzle, type PostgresJsDatabase } from "drizzle-orm/postgres-js"; +import type { TableRelationalConfig } from "drizzle-orm"; +import type postgres from "postgres"; + +type Callback = (tx: Transaction) => unknown; +type Transaction = { + _: { schema: unknown; fullSchema: unknown; tableNamesMap: unknown; session: PgSession }; + query: unknown; + transaction(callback: Callback, ...rest: unknown[]): unknown; +}; + +/** + * `drizzle(client, { schema })` whose transactions build `tx.query` on first + * read instead of at `BEGIN`. + * + * Drizzle constructs one relational query builder per schema table for every + * database object it creates, and it creates one for each transaction and each + * savepoint. With the Paperclip schema that is about 100 KB per transaction, + * for an API that almost no transaction reads. + * + * Transactions are therefore opened through a second Drizzle client on the same + * postgres.js client, created without the schema. `BEGIN`, `SAVEPOINT`, commit, + * rollback and connection handling stay Drizzle's and the driver's own. A + * transaction that does read `tx.query` gets the builders Drizzle would have + * built, bound to that transaction's session, and `tx._` still describes the + * schema. + * + * Both clients and the builders' dialect take Drizzle's defaults. A Drizzle + * option added here (`casing`, `logger`, `cache`) must go to all three. + */ +export function drizzleWithLazyTransactionQueries, TClient extends postgres.Sql>( + client: TClient, + schema: TSchema, +): PostgresJsDatabase & { $client: TClient } { + const db = drizzle(client, { schema }); + const tables = db._.schema; + if (!tables) return db; + const { fullSchema, tableNamesMap } = db._; + const transactions = drizzle(client) as unknown as Transaction; + const dialect = new PgDialect(); + const resolved = (value: unknown): PropertyDescriptor => ({ value, writable: true, enumerable: true, configurable: true }); + const lazyQuery: PropertyDescriptor = { + enumerable: true, + configurable: true, + get(this: Transaction) { + const query: Record = {}; + for (const [name, table] of Object.entries(tables as Record)) { + query[name] = new RelationalQueryBuilder( + fullSchema, tables, tableNamesMap, fullSchema[name] as PgTable, table, dialect, this._.session, + ); + } + Object.defineProperty(this, "query", resolved(query)); + return query; + }, + set(this: Transaction, value: unknown) { + Object.defineProperty(this, "query", resolved(value)); + }, + }; + const within = (callback: Callback): Callback => (tx) => { + tx._.schema = tables; + tx._.fullSchema = fullSchema; + tx._.tableNamesMap = tableNamesMap; + Object.defineProperty(tx, "query", lazyQuery); + const savepoint = tx.transaction; + tx.transaction = function (this: Transaction, nested, ...rest) { + return Reflect.apply(savepoint, this, [within(nested), ...rest]); + }; + return callback(tx); + }; + (db as unknown as Transaction).transaction = (callback, ...rest) => transactions.transaction(within(callback), ...rest); + return db; +}