ReviewOS

also looking at this

stacks/bun-query-builder

fix(client): a builder's writes belong to the builder's own connection

#1065
Merged glennmichael123 wants to merge fix/builder-local-connection into main
2 files +161 -29
packages/bun-query-builder/test/client.transaction-connection.test.tsadded+112-0
Changes to packages/bun-query-builder/test/client.transaction-connection.test.ts
@@ -0,0 +1,112 @@
1/**
2 * Every statement a builder issues must go through the builder's OWN
3 * connection (`_sql`), never the module-global `bunSql`.
4 *
5 * They are the same object for a plain builder, so this is invisible until a
6 * builder is created with a connection of its own — which is exactly what
7 * `db.transaction()` does for its callback. Then the global is a DIFFERENT
8 * pooled session, and ~29 helper methods were using it:
9 *
10 * - A write inside `db.transaction()` autocommitted on that other session and
11 * SURVIVED THE ROLLBACK. The transaction failed, the caller saw the error,
12 * and the row was still in the table. Silent, with no driver error.
13 * - A read inside the transaction could not see the transaction's own
14 * uncommitted rows, so `tx.count()` returned 0 for a row `tx` had just
15 * inserted and read-then-decide logic acted on stale data.
16 *
17 * SQLite cannot catch either one: `bunSql` and the transaction share a single
18 * `bun:sqlite` handle, so the distinction the bug turns on does not exist. It
19 * needs a real pooled driver, so this file is gated on a live Postgres and runs
20 * in a subprocess (an earlier `configureOrm()` elsewhere in the suite pins the
21 * global executor at sqlite and would mask the network path).
22 *
23 * `unsafe()` was fixed for this once already (client.ts, the comment about raw
24 * SQL escaping the transaction); these are the rest of the same family.
25 */
26
27import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
28import { tmpdir } from 'node:os'
29import { join, resolve } from 'node:path'
30import process from 'node:process'
31import { SQL } from 'bun'
32import { describe, expect, it } from 'bun:test'
33
34const PG_URL = `postgres://${process.env.USER}@localhost:5432/postgres`
35
36let pgAvailable = false
37try {
38 const probe = new SQL(PG_URL)
39 await probe.unsafe('SELECT 1')
40 await probe.end()
41 pgAvailable = true
42}
43catch {
44 pgAvailable = false
45}
46
47describe.skipIf(!pgAvailable)('builder-local connection routing', () => {
48 it('keeps transactional writes inside the transaction, and reads inside it current', () => {
49 const srcEntry = resolve(import.meta.dir, '../src/index.ts')
50 const dir = mkdtempSync(join(tmpdir(), 'qb-txconn-'))
51 const scriptPath = join(dir, 'probe.ts')
52
53 writeFileSync(scriptPath, `
54import { SQL } from 'bun'
55import { setConfig, createQueryBuilder, buildDatabaseSchema } from ${JSON.stringify(srcEntry)}
56
57const URL = ${JSON.stringify(PG_URL)}
58const raw = new SQL(URL)
59await raw.unsafe('DROP TABLE IF EXISTS _qb_txconn')
60await raw.unsafe('CREATE TABLE _qb_txconn (id serial primary key, name text)')
61
62setConfig({ dialect: 'postgres', database: { url: URL } })
63const schema = buildDatabaseSchema({
64 Widget: { name: 'Widget', table: '_qb_txconn', primaryKey: 'id', attributes: { id: { validation: { rule: {} } }, name: { validation: { rule: {} } } } },
65})
66const db = createQueryBuilder({ schema })
67
68// A write in a transaction that throws must not outlive the ROLLBACK.
69try {
70 await db.transaction(async (tx) => {
71 await tx.insertGetId('_qb_txconn', { name: 'rolled-back' })
72 throw new Error('deliberate failure')
73 })
74}
75catch {}
76const survivors = await raw.unsafe('SELECT name FROM _qb_txconn')
77
78// A read in a transaction must see that transaction's own uncommitted write.
79let seenInside = -1
80await db.transaction(async (tx) => {
81 await tx.insertGetId('_qb_txconn', { name: 'committed' })
82 seenInside = Number(await tx.count('_qb_txconn'))
83})
84const committed = await raw.unsafe('SELECT name FROM _qb_txconn')
85
86await raw.unsafe('DROP TABLE IF EXISTS _qb_txconn')
87await raw.end()
88
89console.log(JSON.stringify({
90 survivedRollback: survivors.length,
91 seenInside,
92 committed: committed.length,
93}))
94`)
95
96 const proc = Bun.spawnSync({ cmd: ['bun', scriptPath], cwd: dir, stdout: 'pipe', stderr: 'pipe' })
97 const stdout = new TextDecoder().decode(proc.stdout).trim()
98 const stderr = new TextDecoder().decode(proc.stderr).trim()
99 rmSync(dir, { recursive: true, force: true })
100
101 if (proc.exitCode !== 0)
102 throw new Error(`probe exited ${proc.exitCode}: ${stderr || stdout}`)
103
104 const result = JSON.parse(stdout.split('\n').filter(Boolean).at(-1) ?? '{}')
105
106 // Was 1 — the write autocommitted on the global connection and outlived the rollback.
107 expect(result.survivedRollback).toBe(0)
108 // Was 0 — the count ran on the global connection and could not see the tx's row.
109 expect(result.seenInside).toBe(1)
110 expect(result.committed).toBe(1)
111 })
112})