@contember/database 2.2.0-alpha.2 → 2.2.0-alpha.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +23 -1
- package/dist/development/index.cjs +6 -0
- package/dist/development/index.cjs.map +1 -1
- package/dist/development/index.js +7 -1
- package/dist/development/index.js.map +1 -1
- package/dist/development/src/builders/LimitByGroupWrapper.cjs +1 -1
- package/dist/development/src/builders/LimitByGroupWrapper.cjs.map +1 -1
- package/dist/development/src/builders/LimitByGroupWrapper.js +1 -1
- package/dist/development/src/builders/LimitByGroupWrapper.js.map +1 -1
- package/dist/development/src/builders/WindowFunction.cjs +1 -1
- package/dist/development/src/builders/WindowFunction.cjs.map +1 -1
- package/dist/development/src/builders/WindowFunction.js +1 -1
- package/dist/development/src/builders/WindowFunction.js.map +1 -1
- package/dist/development/src/client/AcquiredConnection.cjs +110 -32
- package/dist/development/src/client/AcquiredConnection.cjs.map +1 -1
- package/dist/development/src/client/AcquiredConnection.js +112 -34
- package/dist/development/src/client/AcquiredConnection.js.map +1 -1
- package/dist/development/src/client/Client.cjs +9 -1
- package/dist/development/src/client/Client.cjs.map +1 -1
- package/dist/development/src/client/Client.js +9 -1
- package/dist/development/src/client/Client.js.map +1 -1
- package/dist/development/src/client/Connection.cjs +48 -5
- package/dist/development/src/client/Connection.cjs.map +1 -1
- package/dist/development/src/client/Connection.js +48 -5
- package/dist/development/src/client/Connection.js.map +1 -1
- package/dist/development/src/client/EventManager.cjs +6 -2
- package/dist/development/src/client/EventManager.cjs.map +1 -1
- package/dist/development/src/client/EventManager.js +6 -2
- package/dist/development/src/client/EventManager.js.map +1 -1
- package/dist/development/src/client/RequestMemoryBudget.cjs +237 -0
- package/dist/development/src/client/RequestMemoryBudget.cjs.map +1 -0
- package/dist/development/src/client/RequestMemoryBudget.js +237 -0
- package/dist/development/src/client/RequestMemoryBudget.js.map +1 -0
- package/dist/development/src/client/Transaction.cjs +20 -8
- package/dist/development/src/client/Transaction.cjs.map +1 -1
- package/dist/development/src/client/Transaction.js +21 -9
- package/dist/development/src/client/Transaction.js.map +1 -1
- package/dist/development/src/client/cancelRunningStatement.cjs +32 -0
- package/dist/development/src/client/cancelRunningStatement.cjs.map +1 -0
- package/dist/development/src/client/cancelRunningStatement.js +32 -0
- package/dist/development/src/client/cancelRunningStatement.js.map +1 -0
- package/dist/development/src/client/errors.cjs +12 -1
- package/dist/development/src/client/errors.cjs.map +1 -1
- package/dist/development/src/client/errors.js +12 -1
- package/dist/development/src/client/errors.js.map +1 -1
- package/dist/development/src/utils/pgClientFactory.cjs +4 -1
- package/dist/development/src/utils/pgClientFactory.cjs.map +1 -1
- package/dist/development/src/utils/pgClientFactory.js +4 -1
- package/dist/development/src/utils/pgClientFactory.js.map +1 -1
- package/dist/production/index.cjs +6 -0
- package/dist/production/index.cjs.map +1 -1
- package/dist/production/index.js +7 -1
- package/dist/production/index.js.map +1 -1
- package/dist/production/src/builders/LimitByGroupWrapper.cjs +1 -1
- package/dist/production/src/builders/LimitByGroupWrapper.cjs.map +1 -1
- package/dist/production/src/builders/LimitByGroupWrapper.js +1 -1
- package/dist/production/src/builders/LimitByGroupWrapper.js.map +1 -1
- package/dist/production/src/builders/WindowFunction.cjs +1 -1
- package/dist/production/src/builders/WindowFunction.cjs.map +1 -1
- package/dist/production/src/builders/WindowFunction.js +1 -1
- package/dist/production/src/builders/WindowFunction.js.map +1 -1
- package/dist/production/src/client/AcquiredConnection.cjs +110 -32
- package/dist/production/src/client/AcquiredConnection.cjs.map +1 -1
- package/dist/production/src/client/AcquiredConnection.js +112 -34
- package/dist/production/src/client/AcquiredConnection.js.map +1 -1
- package/dist/production/src/client/Client.cjs +9 -1
- package/dist/production/src/client/Client.cjs.map +1 -1
- package/dist/production/src/client/Client.js +9 -1
- package/dist/production/src/client/Client.js.map +1 -1
- package/dist/production/src/client/Connection.cjs +48 -5
- package/dist/production/src/client/Connection.cjs.map +1 -1
- package/dist/production/src/client/Connection.js +48 -5
- package/dist/production/src/client/Connection.js.map +1 -1
- package/dist/production/src/client/EventManager.cjs +6 -2
- package/dist/production/src/client/EventManager.cjs.map +1 -1
- package/dist/production/src/client/EventManager.js +6 -2
- package/dist/production/src/client/EventManager.js.map +1 -1
- package/dist/production/src/client/RequestMemoryBudget.cjs +237 -0
- package/dist/production/src/client/RequestMemoryBudget.cjs.map +1 -0
- package/dist/production/src/client/RequestMemoryBudget.js +237 -0
- package/dist/production/src/client/RequestMemoryBudget.js.map +1 -0
- package/dist/production/src/client/Transaction.cjs +20 -8
- package/dist/production/src/client/Transaction.cjs.map +1 -1
- package/dist/production/src/client/Transaction.js +21 -9
- package/dist/production/src/client/Transaction.js.map +1 -1
- package/dist/production/src/client/cancelRunningStatement.cjs +32 -0
- package/dist/production/src/client/cancelRunningStatement.cjs.map +1 -0
- package/dist/production/src/client/cancelRunningStatement.js +32 -0
- package/dist/production/src/client/cancelRunningStatement.js.map +1 -0
- package/dist/production/src/client/errors.cjs +12 -1
- package/dist/production/src/client/errors.cjs.map +1 -1
- package/dist/production/src/client/errors.js +12 -1
- package/dist/production/src/client/errors.js.map +1 -1
- package/dist/production/src/utils/pgClientFactory.cjs +4 -1
- package/dist/production/src/utils/pgClientFactory.cjs.map +1 -1
- package/dist/production/src/utils/pgClientFactory.js +4 -1
- package/dist/production/src/utils/pgClientFactory.js.map +1 -1
- package/dist/tests/cases/integration/requestMemoryBudget.test.d.ts +2 -0
- package/dist/tests/cases/integration/requestMemoryBudget.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/acquiredConnection.test.d.ts +2 -0
- package/dist/tests/cases/unit/acquiredConnection.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/createConnectionMockAlt.d.ts +12 -3
- package/dist/tests/cases/unit/createConnectionMockAlt.d.ts.map +1 -1
- package/dist/tests/cases/unit/requestMemoryBudget.test.d.ts +2 -0
- package/dist/tests/cases/unit/requestMemoryBudget.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/staleConnectionRetry.test.d.ts +2 -0
- package/dist/tests/cases/unit/staleConnectionRetry.test.d.ts.map +1 -0
- package/dist/tests/src/tags.d.ts.map +1 -1
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/dist/types/Literal.d.ts.map +1 -1
- package/dist/types/builders/CaseStatement.d.ts.map +1 -1
- package/dist/types/builders/ColumnExpressionFactory.d.ts.map +1 -1
- package/dist/types/builders/Compiler.d.ts.map +1 -1
- package/dist/types/builders/ConditionBuilder.d.ts.map +1 -1
- package/dist/types/builders/DeleteBuilder.d.ts.map +1 -1
- package/dist/types/builders/InsertBuilder.d.ts.map +1 -1
- package/dist/types/builders/LimitByGroupWrapper.d.ts.map +1 -1
- package/dist/types/builders/SelectBuilder.d.ts.map +1 -1
- package/dist/types/builders/UpdateBuilder.d.ts.map +1 -1
- package/dist/types/builders/WindowFunction.d.ts +2 -1
- package/dist/types/builders/WindowFunction.d.ts.map +1 -1
- package/dist/types/builders/internal/Returning.d.ts.map +1 -1
- package/dist/types/builders/internal/Where.d.ts.map +1 -1
- package/dist/types/builders/internal/With.d.ts.map +1 -1
- package/dist/types/client/AcquiredConnection.d.ts +6 -1
- package/dist/types/client/AcquiredConnection.d.ts.map +1 -1
- package/dist/types/client/Client.d.ts +8 -0
- package/dist/types/client/Client.d.ts.map +1 -1
- package/dist/types/client/Connection.d.ts +11 -2
- package/dist/types/client/Connection.d.ts.map +1 -1
- package/dist/types/client/EventManager.d.ts +5 -1
- package/dist/types/client/EventManager.d.ts.map +1 -1
- package/dist/types/client/PgClient.d.ts +13 -2
- package/dist/types/client/PgClient.d.ts.map +1 -1
- package/dist/types/client/Pool.d.ts.map +1 -1
- package/dist/types/client/RequestMemoryBudget.d.ts +41 -0
- package/dist/types/client/RequestMemoryBudget.d.ts.map +1 -0
- package/dist/types/client/ScopeLimitedConnection.d.ts.map +1 -1
- package/dist/types/client/Transaction.d.ts +3 -3
- package/dist/types/client/Transaction.d.ts.map +1 -1
- package/dist/types/client/cancelRunningStatement.d.ts +7 -0
- package/dist/types/client/cancelRunningStatement.d.ts.map +1 -0
- package/dist/types/client/errors.d.ts +5 -0
- package/dist/types/client/errors.d.ts.map +1 -1
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/metadata/DatabaseMetadata.d.ts.map +1 -1
- package/dist/types/metadata/DatabaseMetadataResolver.d.ts.map +1 -1
- package/dist/types/metadata/ForeignKeyConstraintMetadata.d.ts.map +1 -1
- package/dist/types/metadata/IndexMetadata.d.ts.map +1 -1
- package/dist/types/metadata/UniqueConstraintMetadata.d.ts.map +1 -1
- package/dist/types/metadata/stringArrayEquals.d.ts.map +1 -1
- package/dist/types/queryable/DatabaseQuery.d.ts.map +1 -1
- package/dist/types/queryable/DatabaseQueryable.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/dist/types/types.d.ts +15 -0
- package/dist/types/types.d.ts.map +1 -1
- package/dist/types/utils/ConstraintHelper.d.ts.map +1 -1
- package/dist/types/utils/Mutex.d.ts.map +1 -1
- package/dist/types/utils/Semaphore.d.ts.map +1 -1
- package/dist/types/utils/createDatabaseIfNotExists.d.ts.map +1 -1
- package/dist/types/utils/listen.d.ts.map +1 -1
- package/dist/types/utils/pgClientFactory.d.ts +1 -2
- package/dist/types/utils/pgClientFactory.d.ts.map +1 -1
- package/dist/types/utils/retryTransaction.d.ts.map +1 -1
- package/dist/types/utils/sql.d.ts.map +1 -1
- package/dist/types/utils/withDatabaseAdvisoryLock.d.ts.map +1 -1
- package/package.json +4 -3
- package/src/builders/LimitByGroupWrapper.ts +1 -1
- package/src/builders/WindowFunction.ts +3 -2
- package/src/client/AcquiredConnection.ts +131 -33
- package/src/client/Client.ts +11 -1
- package/src/client/Connection.ts +66 -3
- package/src/client/EventManager.ts +11 -1
- package/src/client/PgClient.ts +18 -2
- package/src/client/RequestMemoryBudget.ts +260 -0
- package/src/client/Transaction.ts +21 -8
- package/src/client/cancelRunningStatement.ts +36 -0
- package/src/client/errors.ts +15 -3
- package/src/index.ts +1 -0
- package/src/types.ts +15 -0
- package/src/utils/pgClientFactory.ts +5 -4
- package/tests/cases/integration/requestMemoryBudget.test.ts +296 -0
- package/tests/cases/unit/acquiredConnection.test.ts +209 -0
- package/tests/cases/unit/connection.test.ts +77 -1
- package/tests/cases/unit/createConnectionMockAlt.ts +35 -4
- package/tests/cases/unit/queryBuilder.test.ts +22 -1
- package/tests/cases/unit/requestMemoryBudget.test.ts +287 -0
- package/tests/cases/unit/staleConnectionRetry.test.ts +86 -0
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
import { expect, test } from 'bun:test'
|
|
2
|
+
import { randomUUID } from 'node:crypto'
|
|
3
|
+
import { Connection, EventManager, RequestMemoryBudget, RequestMemoryBudgetExceededError, retryTransaction } from '../../../src/index.js'
|
|
4
|
+
|
|
5
|
+
const databaseUrl = process.env.MEMORY_TEST_DATABASE_URL
|
|
6
|
+
const databaseTest = test.skipIf(!databaseUrl)
|
|
7
|
+
|
|
8
|
+
function createConnection(queryTimeoutMs?: number) {
|
|
9
|
+
if (!databaseUrl) {
|
|
10
|
+
throw new Error('Set MEMORY_TEST_DATABASE_URL to a local PostgreSQL database')
|
|
11
|
+
}
|
|
12
|
+
const url = new URL(databaseUrl)
|
|
13
|
+
return Connection.create({
|
|
14
|
+
host: url.hostname,
|
|
15
|
+
port: Number(url.port || 5432),
|
|
16
|
+
user: decodeURIComponent(url.username),
|
|
17
|
+
password: decodeURIComponent(url.password),
|
|
18
|
+
database: url.pathname.slice(1),
|
|
19
|
+
queryTimeoutMs,
|
|
20
|
+
pool: { maxConnections: 3 },
|
|
21
|
+
}, error => {
|
|
22
|
+
throw error
|
|
23
|
+
})
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
databaseTest('budget interrupts accumulation and the pool serves the next request', async () => {
|
|
27
|
+
const connection = createConnection()
|
|
28
|
+
try {
|
|
29
|
+
const base = connection.createClient('public', {})
|
|
30
|
+
const budget = new RequestMemoryBudget({ warnBytes: 128 * 1024, maxBytes: 256 * 1024 })
|
|
31
|
+
const db = base.withMemoryBudget(budget)
|
|
32
|
+
await expect(db.query('SELECT repeat(?, 1024) AS body FROM generate_series(1, 100000)', ['x']))
|
|
33
|
+
.rejects.toBeInstanceOf(RequestMemoryBudgetExceededError)
|
|
34
|
+
expect(budget.snapshot().databaseRows).toBeLessThan(1000)
|
|
35
|
+
expect((await base.query('SELECT 42 AS value')).rows).toEqual([{ value: 42 }])
|
|
36
|
+
} finally {
|
|
37
|
+
await connection.end()
|
|
38
|
+
}
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
databaseTest('budget aborts a sibling query still waiting for its first row', async () => {
|
|
42
|
+
const connection = createConnection()
|
|
43
|
+
try {
|
|
44
|
+
const budget = new RequestMemoryBudget({ warnBytes: 128 * 1024, maxBytes: 256 * 1024 })
|
|
45
|
+
const db = connection.createClient('public', {}).withMemoryBudget(budget)
|
|
46
|
+
const start = Date.now()
|
|
47
|
+
const results = await Promise.allSettled([
|
|
48
|
+
db.query('SELECT pg_sleep(3)'),
|
|
49
|
+
db.query('SELECT repeat(?, 1024) AS body FROM generate_series(1, 100000)', ['x']),
|
|
50
|
+
])
|
|
51
|
+
for (const result of results) {
|
|
52
|
+
expect(result.status).toBe('rejected')
|
|
53
|
+
if (result.status === 'rejected') {
|
|
54
|
+
expect(result.reason).toBeInstanceOf(RequestMemoryBudgetExceededError)
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
expect(Date.now() - start).toBeLessThan(2500)
|
|
58
|
+
} finally {
|
|
59
|
+
await connection.end()
|
|
60
|
+
}
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
databaseTest('budget cancels a sibling statement on the server, not only its socket', async () => {
|
|
64
|
+
const connection = createConnection()
|
|
65
|
+
try {
|
|
66
|
+
const base = connection.createClient('public', {})
|
|
67
|
+
const budget = new RequestMemoryBudget({ warnBytes: 128 * 1024, maxBytes: 256 * 1024 })
|
|
68
|
+
const db = base.withMemoryBudget(budget)
|
|
69
|
+
const marker = `memory_budget_${randomUUID().replaceAll('-', '')}`
|
|
70
|
+
const results = await Promise.allSettled([
|
|
71
|
+
db.query(`SELECT pg_sleep(30) AS ${marker}`),
|
|
72
|
+
db.query('SELECT repeat(?, 1024) AS body FROM generate_series(1, 100000)', ['x']),
|
|
73
|
+
])
|
|
74
|
+
expect(results.map(it => it.status)).toEqual(['rejected', 'rejected'])
|
|
75
|
+
|
|
76
|
+
const deadline = Date.now() + 2000
|
|
77
|
+
let running = 1
|
|
78
|
+
while (running > 0 && Date.now() < deadline) {
|
|
79
|
+
await new Promise(resolve => setTimeout(resolve, 50))
|
|
80
|
+
const activity = await base.query<{ count: number }>(
|
|
81
|
+
'SELECT count(*)::int AS count FROM pg_stat_activity WHERE query LIKE ? AND pid <> pg_backend_pid()',
|
|
82
|
+
[`%${marker}%`],
|
|
83
|
+
)
|
|
84
|
+
running = activity.rows[0].count
|
|
85
|
+
}
|
|
86
|
+
expect(running).toBe(0)
|
|
87
|
+
} finally {
|
|
88
|
+
await connection.end()
|
|
89
|
+
}
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
databaseTest('row observation preserves pg query timeouts and row accumulation', async () => {
|
|
93
|
+
const connection = createConnection(100)
|
|
94
|
+
try {
|
|
95
|
+
const budget = new RequestMemoryBudget({ warnBytes: 512 * 1024, maxBytes: 1024 * 1024 })
|
|
96
|
+
const db = connection.createClient('public', {}).withMemoryBudget(budget)
|
|
97
|
+
expect((await db.query('SELECT i FROM generate_series(1, 10) i')).rows).toHaveLength(10)
|
|
98
|
+
await expect(db.query('SELECT pg_sleep(3)')).rejects.toThrow('Query read timeout')
|
|
99
|
+
expect((await db.query('SELECT 42 AS value')).rows).toEqual([{ value: 42 }])
|
|
100
|
+
} finally {
|
|
101
|
+
await connection.end()
|
|
102
|
+
}
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
databaseTest('hydration budget exhaustion rolls back a transaction without closing its enclosing scope', async () => {
|
|
106
|
+
const connection = createConnection()
|
|
107
|
+
try {
|
|
108
|
+
await connection.createClient('public', {}).scope(async base => {
|
|
109
|
+
await base.query('CREATE TEMP TABLE memory_budget_hydration (value integer)')
|
|
110
|
+
const budget = new RequestMemoryBudget({ warnBytes: 512, maxBytes: 1024 })
|
|
111
|
+
await expect(
|
|
112
|
+
base.withMemoryBudget(budget).transaction(async transaction => {
|
|
113
|
+
await transaction.query('INSERT INTO memory_budget_hydration VALUES (42)')
|
|
114
|
+
budget.addHydrationBytes(1024)
|
|
115
|
+
}),
|
|
116
|
+
).rejects.toBeInstanceOf(RequestMemoryBudgetExceededError)
|
|
117
|
+
expect((await base.query('SELECT * FROM memory_budget_hydration')).rows).toEqual([])
|
|
118
|
+
})
|
|
119
|
+
} finally {
|
|
120
|
+
await connection.end()
|
|
121
|
+
}
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
databaseTest('budgets stay request-local and cannot cancel a connection reused by another request', async () => {
|
|
125
|
+
const connection = createConnection()
|
|
126
|
+
try {
|
|
127
|
+
const base = connection.createClient('public', {})
|
|
128
|
+
const failedBudget = new RequestMemoryBudget({ warnBytes: 512, maxBytes: 1024 })
|
|
129
|
+
const healthyBudget = new RequestMemoryBudget({ warnBytes: 512, maxBytes: 32768 })
|
|
130
|
+
const [, healthyPid] = await Promise.all([
|
|
131
|
+
expect(base.withMemoryBudget(failedBudget).query("SELECT repeat('x', 2048)"))
|
|
132
|
+
.rejects.toBeInstanceOf(RequestMemoryBudgetExceededError),
|
|
133
|
+
base.withMemoryBudget(healthyBudget).scope(async scoped => {
|
|
134
|
+
expect(scoped.eventManager.memoryBudget).toBe(healthyBudget)
|
|
135
|
+
expect(scoped.forSchema('public').eventManager.memoryBudget).toBe(healthyBudget)
|
|
136
|
+
await scoped.transaction(async transaction => {
|
|
137
|
+
expect(transaction.eventManager.memoryBudget).toBe(healthyBudget)
|
|
138
|
+
await transaction.transaction(async savepoint => {
|
|
139
|
+
expect(savepoint.eventManager.memoryBudget).toBe(healthyBudget)
|
|
140
|
+
expect((await savepoint.query('SELECT 42 AS value')).rows).toEqual([{ value: 42 }])
|
|
141
|
+
})
|
|
142
|
+
})
|
|
143
|
+
return (await scoped.query<{ pid: number }>('SELECT pg_backend_pid() AS pid')).rows[0].pid
|
|
144
|
+
}),
|
|
145
|
+
])
|
|
146
|
+
expect(healthyBudget.exceeded).toBe(false)
|
|
147
|
+
expect(base.eventManager.memoryBudget).toBeUndefined()
|
|
148
|
+
expect(connection.eventManager.memoryBudget).toBeUndefined()
|
|
149
|
+
await base.scope(async reused => {
|
|
150
|
+
expect((await reused.query('SELECT pg_backend_pid() AS pid')).rows).toEqual([{ pid: healthyPid }])
|
|
151
|
+
expect(() => healthyBudget.addHydrationBytes(32768)).toThrow(RequestMemoryBudgetExceededError)
|
|
152
|
+
expect((await reused.query('SELECT 42 AS value')).rows).toEqual([{ value: 42 }])
|
|
153
|
+
})
|
|
154
|
+
} finally {
|
|
155
|
+
await connection.end()
|
|
156
|
+
}
|
|
157
|
+
})
|
|
158
|
+
|
|
159
|
+
databaseTest.each([false, true])('reads exceeding the budget roll back writes without retrying (savepoint: %s)', async savepoint => {
|
|
160
|
+
const connection = createConnection()
|
|
161
|
+
const base = connection.createClient('public', {})
|
|
162
|
+
const table = `memory_budget_${randomUUID().replaceAll('-', '')}`
|
|
163
|
+
try {
|
|
164
|
+
await base.query(`CREATE TABLE "${table}" (value integer)`)
|
|
165
|
+
const budget = new RequestMemoryBudget({ warnBytes: 128 * 1024, maxBytes: 256 * 1024 })
|
|
166
|
+
const db = base.withMemoryBudget(budget)
|
|
167
|
+
let attempts = 0
|
|
168
|
+
await expect(retryTransaction(async () => {
|
|
169
|
+
attempts++
|
|
170
|
+
await db.transaction(async transaction => {
|
|
171
|
+
await transaction.query(`INSERT INTO "${table}" VALUES (42)`)
|
|
172
|
+
const sql = "SELECT repeat('x', 1024) AS body FROM generate_series(1, 100000)"
|
|
173
|
+
if (savepoint) {
|
|
174
|
+
await transaction.transaction(inner => inner.query(sql))
|
|
175
|
+
} else {
|
|
176
|
+
await transaction.query(sql)
|
|
177
|
+
}
|
|
178
|
+
})
|
|
179
|
+
}, () => {})).rejects.toBeInstanceOf(RequestMemoryBudgetExceededError)
|
|
180
|
+
expect(attempts).toBe(1)
|
|
181
|
+
expect((await base.query(`SELECT * FROM "${table}"`)).rows).toEqual([])
|
|
182
|
+
await base.withMemoryBudget(new RequestMemoryBudget({ warnBytes: 512, maxBytes: 256 * 1024 })).transaction(async transaction => {
|
|
183
|
+
await transaction.query(`INSERT INTO "${table}" VALUES (43)`)
|
|
184
|
+
await transaction.query('SELECT i FROM generate_series(1, 10) i')
|
|
185
|
+
})
|
|
186
|
+
expect((await base.query(`SELECT * FROM "${table}"`)).rows).toEqual([{ value: 43 }])
|
|
187
|
+
} finally {
|
|
188
|
+
try {
|
|
189
|
+
await base.query(`DROP TABLE IF EXISTS "${table}"`)
|
|
190
|
+
} finally {
|
|
191
|
+
await connection.end()
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
})
|
|
195
|
+
|
|
196
|
+
databaseTest.each([false, true])('a budget-terminated transaction reports one budget error and no SQL error (savepoint: %s)', async savepoint => {
|
|
197
|
+
const connection = createConnection()
|
|
198
|
+
try {
|
|
199
|
+
const queryErrors: Error[] = []
|
|
200
|
+
connection.eventManager.on(EventManager.Event.queryError, (query, error) => {
|
|
201
|
+
queryErrors.push(error)
|
|
202
|
+
})
|
|
203
|
+
const budget = new RequestMemoryBudget({ warnBytes: 128 * 1024, maxBytes: 256 * 1024 })
|
|
204
|
+
const db = connection.createClient('public', {}).withMemoryBudget(budget)
|
|
205
|
+
const sql = "SELECT repeat('x', 1024) AS body FROM generate_series(1, 100000)"
|
|
206
|
+
await expect(db.transaction(async transaction => {
|
|
207
|
+
if (savepoint) {
|
|
208
|
+
await transaction.transaction(inner => inner.query(sql))
|
|
209
|
+
} else {
|
|
210
|
+
await transaction.query(sql)
|
|
211
|
+
}
|
|
212
|
+
})).rejects.toBeInstanceOf(RequestMemoryBudgetExceededError)
|
|
213
|
+
expect(queryErrors).toHaveLength(1)
|
|
214
|
+
expect(queryErrors[0]).toBeInstanceOf(RequestMemoryBudgetExceededError)
|
|
215
|
+
} finally {
|
|
216
|
+
await connection.end()
|
|
217
|
+
}
|
|
218
|
+
})
|
|
219
|
+
|
|
220
|
+
databaseTest('queries queued behind the one that exhausted the budget report the budget, not the terminated connection', async () => {
|
|
221
|
+
const connection = createConnection()
|
|
222
|
+
try {
|
|
223
|
+
const budget = new RequestMemoryBudget({ warnBytes: 128 * 1024, maxBytes: 256 * 1024 })
|
|
224
|
+
const bound = connection.createClient('public', {}).withMemoryBudget(budget, { chargeRows: false })
|
|
225
|
+
let results: PromiseSettledResult<unknown>[] = []
|
|
226
|
+
// The commit of the terminated connection fails with the budget error as well.
|
|
227
|
+
await expect(bound.transaction(async transaction => {
|
|
228
|
+
const charged = transaction.withMemoryBudget(budget, { chargeRows: true })
|
|
229
|
+
results = await Promise.allSettled([
|
|
230
|
+
charged.query("SELECT repeat('x', 1024) AS body FROM generate_series(1, 100000)"),
|
|
231
|
+
transaction.query('SELECT 1'),
|
|
232
|
+
charged.query('SELECT 2'),
|
|
233
|
+
])
|
|
234
|
+
})).rejects.toBeInstanceOf(RequestMemoryBudgetExceededError)
|
|
235
|
+
expect(results).toHaveLength(3)
|
|
236
|
+
for (const result of results) {
|
|
237
|
+
expect(result.status).toBe('rejected')
|
|
238
|
+
if (result.status === 'rejected') {
|
|
239
|
+
expect(result.reason).toBeInstanceOf(RequestMemoryBudgetExceededError)
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
} finally {
|
|
243
|
+
await connection.end()
|
|
244
|
+
}
|
|
245
|
+
})
|
|
246
|
+
|
|
247
|
+
databaseTest('a failed rollback is reported when the budget left the connection alive', async () => {
|
|
248
|
+
const connection = createConnection()
|
|
249
|
+
try {
|
|
250
|
+
const budget = new RequestMemoryBudget({ warnBytes: 512, maxBytes: 1024 })
|
|
251
|
+
const db = connection.createClient('public', {}).withMemoryBudget(budget)
|
|
252
|
+
await expect(db.transaction(async transaction => {
|
|
253
|
+
await transaction.transaction(async inner => {
|
|
254
|
+
// Releasing the savepoint behind its back makes the following ROLLBACK TO SAVEPOINT fail.
|
|
255
|
+
await inner.query('RELEASE SAVEPOINT "savepoint_1"')
|
|
256
|
+
budget.addHydrationBytes(1024)
|
|
257
|
+
})
|
|
258
|
+
})).rejects.toThrow('savepoint "savepoint_1" does not exist')
|
|
259
|
+
} finally {
|
|
260
|
+
await connection.end()
|
|
261
|
+
}
|
|
262
|
+
})
|
|
263
|
+
|
|
264
|
+
databaseTest('a charged query fires paired query events, also when it exceeds the budget', async () => {
|
|
265
|
+
const connection = createConnection()
|
|
266
|
+
try {
|
|
267
|
+
const log: string[] = []
|
|
268
|
+
const starts: Connection.Query[] = []
|
|
269
|
+
const pairs: Connection.Query[] = []
|
|
270
|
+
connection.eventManager.on(EventManager.Event.queryStart, query => {
|
|
271
|
+
log.push(`start ${query.sql}`)
|
|
272
|
+
starts.push(query)
|
|
273
|
+
})
|
|
274
|
+
connection.eventManager.on(EventManager.Event.queryEnd, query => {
|
|
275
|
+
log.push(`end ${query.sql}`)
|
|
276
|
+
pairs.push(query)
|
|
277
|
+
})
|
|
278
|
+
connection.eventManager.on(EventManager.Event.queryError, (query, error) => {
|
|
279
|
+
log.push(`error ${query.sql} ${error.constructor.name}`)
|
|
280
|
+
pairs.push(query)
|
|
281
|
+
})
|
|
282
|
+
const budget = new RequestMemoryBudget({ warnBytes: 128 * 1024, maxBytes: 256 * 1024 })
|
|
283
|
+
const db = connection.createClient('public', {}).withMemoryBudget(budget)
|
|
284
|
+
const small = 'SELECT 1 AS value'
|
|
285
|
+
const large = "SELECT repeat('x', 1024) AS body FROM generate_series(1, 100000)"
|
|
286
|
+
|
|
287
|
+
await db.query(small)
|
|
288
|
+
await expect(db.query(large)).rejects.toBeInstanceOf(RequestMemoryBudgetExceededError)
|
|
289
|
+
|
|
290
|
+
expect(log).toEqual([`start ${small}`, `end ${small}`, `start ${large}`, `error ${large} RequestMemoryBudgetExceededError`])
|
|
291
|
+
expect(pairs[0]).toBe(starts[0])
|
|
292
|
+
expect(pairs[1]).toBe(starts[1])
|
|
293
|
+
} finally {
|
|
294
|
+
await connection.end()
|
|
295
|
+
}
|
|
296
|
+
})
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { expect, it } from 'bun:test'
|
|
2
|
+
import EventEmitter from 'node:events'
|
|
3
|
+
import { Connection, EventManager, InvalidDataError, QueryError, RequestMemoryBudget, RequestMemoryBudgetExceededError } from '../../../src/index.js'
|
|
4
|
+
import { AcquiredConnection } from '../../../src/client/AcquiredConnection.js'
|
|
5
|
+
import { PgClient } from '../../../src/client/PgClient.js'
|
|
6
|
+
import { MutexDeadlockError } from '../../../src/utils/index.js'
|
|
7
|
+
|
|
8
|
+
const createPgClientMock = (handler: (sql: string) => Promise<any>): PgClient =>
|
|
9
|
+
new class extends EventEmitter {
|
|
10
|
+
readonly host = 'unused'
|
|
11
|
+
readonly port = 5432
|
|
12
|
+
readonly processID = null
|
|
13
|
+
readonly secretKey = null
|
|
14
|
+
|
|
15
|
+
connect() {
|
|
16
|
+
return Promise.resolve()
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
end() {
|
|
20
|
+
return Promise.resolve()
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async query(sql: string): Promise<any> {
|
|
24
|
+
return await handler(sql)
|
|
25
|
+
}
|
|
26
|
+
}()
|
|
27
|
+
|
|
28
|
+
interface RecordedEvents {
|
|
29
|
+
log: string[]
|
|
30
|
+
starts: Connection.Query[]
|
|
31
|
+
ends: Connection.Query[]
|
|
32
|
+
errors: Connection.Query[]
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const recordEvents = (eventManager: EventManager): RecordedEvents => {
|
|
36
|
+
const recorded: RecordedEvents = { log: [], starts: [], ends: [], errors: [] }
|
|
37
|
+
eventManager.on(EventManager.Event.queryStart, query => {
|
|
38
|
+
recorded.log.push(`start ${query.sql}`)
|
|
39
|
+
recorded.starts.push(query)
|
|
40
|
+
})
|
|
41
|
+
eventManager.on(EventManager.Event.queryEnd, query => {
|
|
42
|
+
recorded.log.push(`end ${query.sql}`)
|
|
43
|
+
recorded.ends.push(query)
|
|
44
|
+
})
|
|
45
|
+
eventManager.on(EventManager.Event.queryError, query => {
|
|
46
|
+
recorded.log.push(`error ${query.sql}`)
|
|
47
|
+
recorded.errors.push(query)
|
|
48
|
+
})
|
|
49
|
+
return recorded
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
it('fires queryEnd with the same event object as queryStart', async () => {
|
|
53
|
+
const eventManager = new EventManager()
|
|
54
|
+
const recorded = recordEvents(eventManager)
|
|
55
|
+
const connection = new AcquiredConnection(
|
|
56
|
+
createPgClientMock(async () => {
|
|
57
|
+
recorded.log.push('execute')
|
|
58
|
+
return { rows: [], rowCount: 0 }
|
|
59
|
+
}),
|
|
60
|
+
eventManager,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
await connection.query('SELECT 1')
|
|
64
|
+
|
|
65
|
+
expect(recorded.log).toStrictEqual(['start SELECT 1', 'execute', 'end SELECT 1'])
|
|
66
|
+
expect(recorded.starts).toHaveLength(1)
|
|
67
|
+
expect(recorded.ends[0]).toBe(recorded.starts[0])
|
|
68
|
+
expect(recorded.errors).toStrictEqual([])
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
it('fires queryError with the same event object as queryStart', async () => {
|
|
72
|
+
const eventManager = new EventManager()
|
|
73
|
+
const recorded = recordEvents(eventManager)
|
|
74
|
+
const connection = new AcquiredConnection(
|
|
75
|
+
createPgClientMock(async () => {
|
|
76
|
+
recorded.log.push('execute')
|
|
77
|
+
throw new Error('query failed')
|
|
78
|
+
}),
|
|
79
|
+
eventManager,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
await expect(connection.query('SELECT 1')).rejects.toThrow(QueryError)
|
|
83
|
+
|
|
84
|
+
expect(recorded.log).toStrictEqual(['start SELECT 1', 'execute', 'error SELECT 1'])
|
|
85
|
+
expect(recorded.starts).toHaveLength(1)
|
|
86
|
+
expect(recorded.errors[0]).toBe(recorded.starts[0])
|
|
87
|
+
expect(recorded.ends).toStrictEqual([])
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
it('fires queryStart before waiting for the connection mutex', async () => {
|
|
91
|
+
const eventManager = new EventManager()
|
|
92
|
+
const recorded = recordEvents(eventManager)
|
|
93
|
+
let unblock: () => void = () => null
|
|
94
|
+
const blocker = new Promise<void>(resolve => {
|
|
95
|
+
unblock = resolve
|
|
96
|
+
})
|
|
97
|
+
const connection = new AcquiredConnection(
|
|
98
|
+
createPgClientMock(async sql => {
|
|
99
|
+
if (sql === 'SELECT 1') {
|
|
100
|
+
await blocker
|
|
101
|
+
}
|
|
102
|
+
return { rows: [], rowCount: 0 }
|
|
103
|
+
}),
|
|
104
|
+
eventManager,
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
const first = connection.query('SELECT 1')
|
|
108
|
+
const second = connection.query('SELECT 2')
|
|
109
|
+
|
|
110
|
+
expect(recorded.log).toStrictEqual(['start SELECT 1', 'start SELECT 2'])
|
|
111
|
+
|
|
112
|
+
unblock()
|
|
113
|
+
await Promise.all([first, second])
|
|
114
|
+
|
|
115
|
+
expect(recorded.log).toStrictEqual(['start SELECT 1', 'start SELECT 2', 'end SELECT 1', 'end SELECT 2'])
|
|
116
|
+
expect(recorded.ends[0]).toBe(recorded.starts[0])
|
|
117
|
+
expect(recorded.ends[1]).toBe(recorded.starts[1])
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
it('fires queryError when the mutex deadlocks', async () => {
|
|
121
|
+
const eventManager = new EventManager()
|
|
122
|
+
const recorded = recordEvents(eventManager)
|
|
123
|
+
const connection = new AcquiredConnection(
|
|
124
|
+
createPgClientMock(async () => {
|
|
125
|
+
recorded.log.push('execute')
|
|
126
|
+
return { rows: [], rowCount: 0 }
|
|
127
|
+
}),
|
|
128
|
+
eventManager,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
await expect(connection.scope(async () => await connection.query('SELECT 1'))).rejects.toThrow(MutexDeadlockError)
|
|
132
|
+
|
|
133
|
+
expect(recorded.log).toStrictEqual(['start SELECT 1', 'error SELECT 1'])
|
|
134
|
+
expect(recorded.errors[0]).toBe(recorded.starts[0])
|
|
135
|
+
expect(recorded.ends).toStrictEqual([])
|
|
136
|
+
})
|
|
137
|
+
|
|
138
|
+
it('refuses a query of an exhausted budget before firing any event', async () => {
|
|
139
|
+
const budget = new RequestMemoryBudget({ warnBytes: 512, maxBytes: 1024 })
|
|
140
|
+
const eventManager = new EventManager(null, budget, false)
|
|
141
|
+
const recorded = recordEvents(eventManager)
|
|
142
|
+
const connection = new AcquiredConnection(
|
|
143
|
+
createPgClientMock(async () => {
|
|
144
|
+
recorded.log.push('execute')
|
|
145
|
+
return { rows: [], rowCount: 0 }
|
|
146
|
+
}),
|
|
147
|
+
eventManager,
|
|
148
|
+
)
|
|
149
|
+
expect(() => budget.addHydrationBytes(2048)).toThrow(RequestMemoryBudgetExceededError)
|
|
150
|
+
|
|
151
|
+
await expect(connection.query('SELECT 1')).rejects.toBeInstanceOf(RequestMemoryBudgetExceededError)
|
|
152
|
+
|
|
153
|
+
expect(recorded.log).toStrictEqual([])
|
|
154
|
+
})
|
|
155
|
+
|
|
156
|
+
for (
|
|
157
|
+
const [code, description] of [['22P02', 'invalid text representation'], ['22007', 'invalid datetime format'], ['22008', 'datetime field overflow']]
|
|
158
|
+
) {
|
|
159
|
+
it(`translates ${description} (${code}) to InvalidDataError`, async () => {
|
|
160
|
+
const connection = new AcquiredConnection(
|
|
161
|
+
createPgClientMock(async () => {
|
|
162
|
+
throw Object.assign(new Error('invalid input'), { code })
|
|
163
|
+
}),
|
|
164
|
+
new EventManager(),
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
await expect(connection.query('SELECT 1')).rejects.toThrow(InvalidDataError)
|
|
168
|
+
})
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
it('puts the PostgreSQL detail and hint of a failed query into the error message', async () => {
|
|
172
|
+
const connection = new AcquiredConnection(
|
|
173
|
+
createPgClientMock(async () => {
|
|
174
|
+
throw Object.assign(new Error('cannot drop column otp_uri of table person because other objects depend on it'), {
|
|
175
|
+
code: '2BP01',
|
|
176
|
+
detail: 'view app.person_otp depends on column otp_uri of table person',
|
|
177
|
+
hint: 'Use DROP ... CASCADE to drop the dependent objects too.',
|
|
178
|
+
})
|
|
179
|
+
}),
|
|
180
|
+
new EventManager(),
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
const error = await connection.query('ALTER TABLE person DROP COLUMN otp_uri').catch(e => e)
|
|
184
|
+
if (!(error instanceof QueryError)) {
|
|
185
|
+
throw error
|
|
186
|
+
}
|
|
187
|
+
expect(error.message).toBe(
|
|
188
|
+
'Database query error: cannot drop column otp_uri of table person because other objects depend on it\n'
|
|
189
|
+
+ 'Detail: view app.person_otp depends on column otp_uri of table person\n'
|
|
190
|
+
+ 'Hint: Use DROP ... CASCADE to drop the dependent objects too.\n'
|
|
191
|
+
+ 'SQL: ALTER TABLE person DROP COLUMN otp_uri\n'
|
|
192
|
+
+ 'parameters: ',
|
|
193
|
+
)
|
|
194
|
+
})
|
|
195
|
+
|
|
196
|
+
it('leaves detail and hint out of the error message when PostgreSQL sends none', async () => {
|
|
197
|
+
const connection = new AcquiredConnection(
|
|
198
|
+
createPgClientMock(async () => {
|
|
199
|
+
throw Object.assign(new Error('relation "missing" does not exist'), { code: '42P01', detail: undefined, hint: undefined })
|
|
200
|
+
}),
|
|
201
|
+
new EventManager(),
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
const error = await connection.query('SELECT * FROM missing').catch(e => e)
|
|
205
|
+
if (!(error instanceof QueryError)) {
|
|
206
|
+
throw error
|
|
207
|
+
}
|
|
208
|
+
expect(error.message).toBe('Database query error: relation "missing" does not exist\nSQL: SELECT * FROM missing\nparameters: ')
|
|
209
|
+
})
|
|
@@ -1,7 +1,15 @@
|
|
|
1
1
|
import { expect, it } from 'bun:test'
|
|
2
|
-
import { MutexDeadlockError } from '../../../src/utils/index.js'
|
|
2
|
+
import { MutexDeadlockError, retryTransaction } from '../../../src/utils/index.js'
|
|
3
|
+
import { SerializationFailureError } from '../../../src/client/index.js'
|
|
4
|
+
import { ClientErrorCodes } from '../../../src/client/errorCodes.js'
|
|
3
5
|
import { createConnectionMockAlt } from './createConnectionMockAlt.js'
|
|
4
6
|
|
|
7
|
+
class PgError extends Error {
|
|
8
|
+
constructor(public readonly code: string) {
|
|
9
|
+
super(`PostgreSQL error ${code}`)
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
5
13
|
it('support nested scope', async () => {
|
|
6
14
|
const [connection, end] = createConnectionMockAlt(
|
|
7
15
|
[{ sql: 'SELECT 1' }],
|
|
@@ -147,3 +155,71 @@ it('detects deadlock', async () => {
|
|
|
147
155
|
await expect(connection.scope(async c1 => c1.scope(async () => await c1.query('SELECT 1')))).rejects.toThrow(MutexDeadlockError)
|
|
148
156
|
end()
|
|
149
157
|
})
|
|
158
|
+
|
|
159
|
+
it('rejects closing a transaction twice', async () => {
|
|
160
|
+
const [connection, end] = createConnectionMockAlt(
|
|
161
|
+
[{ sql: 'BEGIN' }, { sql: 'ROLLBACK' }],
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
await connection.transaction(async trx => {
|
|
165
|
+
await trx.rollback()
|
|
166
|
+
await expect(trx.rollback()).rejects.toThrow('Transaction is already closed')
|
|
167
|
+
await expect(trx.commit()).rejects.toThrow('Transaction is already closed')
|
|
168
|
+
})
|
|
169
|
+
end()
|
|
170
|
+
})
|
|
171
|
+
|
|
172
|
+
it('rejects closing a savepoint twice', async () => {
|
|
173
|
+
const [connection, end] = createConnectionMockAlt(
|
|
174
|
+
[
|
|
175
|
+
{ sql: 'BEGIN' },
|
|
176
|
+
{ sql: 'SAVEPOINT "savepoint_1"' },
|
|
177
|
+
{ sql: 'RELEASE SAVEPOINT "savepoint_1"' },
|
|
178
|
+
{ sql: 'COMMIT', result: { command: 'COMMIT' } },
|
|
179
|
+
],
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
await connection.transaction(async trx => {
|
|
183
|
+
await trx.transaction(async savepoint => {
|
|
184
|
+
await savepoint.commit()
|
|
185
|
+
await expect(savepoint.rollback()).rejects.toThrow('Savepoint savepoint_1 is already closed.')
|
|
186
|
+
})
|
|
187
|
+
})
|
|
188
|
+
end()
|
|
189
|
+
})
|
|
190
|
+
|
|
191
|
+
it('maps a PostgreSQL deadlock to a serialization failure', async () => {
|
|
192
|
+
const [connection, end] = createConnectionMockAlt([{ sql: 'SELECT 1', error: new PgError(ClientErrorCodes.T_R_DEADLOCK_DETECTED) }])
|
|
193
|
+
|
|
194
|
+
await expect(connection.query('SELECT 1')).rejects.toBeInstanceOf(SerializationFailureError)
|
|
195
|
+
end()
|
|
196
|
+
})
|
|
197
|
+
|
|
198
|
+
it('retries a transaction aborted by a PostgreSQL deadlock', async () => {
|
|
199
|
+
// a scope that throws disposes its connection, so the retry runs on a new one
|
|
200
|
+
const [connection, end] = createConnectionMockAlt(
|
|
201
|
+
[
|
|
202
|
+
{ sql: 'BEGIN' },
|
|
203
|
+
{ sql: 'UPDATE t SET v = 1', error: new PgError(ClientErrorCodes.T_R_DEADLOCK_DETECTED) },
|
|
204
|
+
{ sql: 'ROLLBACK' },
|
|
205
|
+
],
|
|
206
|
+
[
|
|
207
|
+
{ sql: 'BEGIN' },
|
|
208
|
+
{ sql: 'UPDATE t SET v = 1', result: { rowCount: 1 } },
|
|
209
|
+
{ sql: 'COMMIT', result: { command: 'COMMIT' } },
|
|
210
|
+
],
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
let attempts = 0
|
|
214
|
+
await retryTransaction(
|
|
215
|
+
() =>
|
|
216
|
+
connection.transaction(async trx => {
|
|
217
|
+
attempts++
|
|
218
|
+
await trx.query('UPDATE t SET v = 1')
|
|
219
|
+
}),
|
|
220
|
+
() => {},
|
|
221
|
+
{ minTimeout: 0, maxTimeout: 0 },
|
|
222
|
+
)
|
|
223
|
+
expect(attempts).toBe(2)
|
|
224
|
+
end()
|
|
225
|
+
})
|
|
@@ -1,13 +1,38 @@
|
|
|
1
|
-
import { Connection, Pool } from '../../../src/index.js'
|
|
1
|
+
import { Connection, Pool, PoolConfig } from '../../../src/index.js'
|
|
2
2
|
import { PgClient } from '../../../src/client/PgClient.js'
|
|
3
3
|
import EventEmitter from 'node:events'
|
|
4
4
|
import { expect } from 'bun:test'
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
// `error` rejects the query; with `lost`, the client first emits `error` as pg does when the server closes the connection.
|
|
7
|
+
type MockQuery = { sql: string; timeout?: number; result?: any; error?: Error; lost?: boolean }
|
|
8
|
+
|
|
9
|
+
export const createConnectionMockAlt = (...queries: MockQuery[][]): [Connection, () => void] => {
|
|
10
|
+
return createConnectionMockAltWithPool({}, ...queries)
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export const createConnectionMockAltWithPool = (
|
|
14
|
+
poolConfig: Partial<Omit<PoolConfig, 'logError'>>,
|
|
15
|
+
...queries: MockQuery[][]
|
|
16
|
+
): [Connection, () => void] => {
|
|
17
|
+
return createConnectionMockAltWithOptions({ pool: poolConfig }, ...queries)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export const createConnectionMockAltWithOptions = (
|
|
21
|
+
{ pool: poolConfig = {}, connection: connectionOptions = {} }: {
|
|
22
|
+
pool?: Partial<Omit<PoolConfig, 'logError'>>
|
|
23
|
+
connection?: Connection.Options
|
|
24
|
+
},
|
|
25
|
+
...queries: MockQuery[][]
|
|
26
|
+
): [Connection, () => void] => {
|
|
7
27
|
const connectionMocks: (PgClient & { assertEmpty: () => void })[] = []
|
|
8
28
|
for (const queriesSet of queries) {
|
|
9
29
|
connectionMocks.push(
|
|
10
30
|
new class extends EventEmitter {
|
|
31
|
+
readonly host = 'unused'
|
|
32
|
+
readonly port = 5432
|
|
33
|
+
readonly processID = null
|
|
34
|
+
readonly secretKey = null
|
|
35
|
+
|
|
11
36
|
connect() {
|
|
12
37
|
return Promise.resolve()
|
|
13
38
|
}
|
|
@@ -21,6 +46,12 @@ export const createConnectionMockAlt = (...queries: { sql: string; timeout?: num
|
|
|
21
46
|
expect(query).toBeDefined()
|
|
22
47
|
expect(sql).toEqual(query?.sql as string)
|
|
23
48
|
await new Promise<void>(resolve => setTimeout(resolve, query?.timeout ?? 1))
|
|
49
|
+
if (query?.lost) {
|
|
50
|
+
this.emit('error', query.error)
|
|
51
|
+
}
|
|
52
|
+
if (query?.error) {
|
|
53
|
+
throw query.error
|
|
54
|
+
}
|
|
24
55
|
|
|
25
56
|
return query?.result
|
|
26
57
|
}
|
|
@@ -36,9 +67,9 @@ export const createConnectionMockAlt = (...queries: { sql: string; timeout?: num
|
|
|
36
67
|
return connectionMocks.shift() ?? (() => {
|
|
37
68
|
throw new Error('No connection')
|
|
38
69
|
})()
|
|
39
|
-
}, { logError: () => null })
|
|
70
|
+
}, { ...poolConfig, logError: () => null })
|
|
40
71
|
return [
|
|
41
|
-
new Connection(pool),
|
|
72
|
+
new Connection(pool, undefined, connectionOptions),
|
|
42
73
|
() => {
|
|
43
74
|
allMocks.forEach(it => it.assertEmpty())
|
|
44
75
|
},
|
|
@@ -339,6 +339,27 @@ test('query builder: constructs window function', async () => {
|
|
|
339
339
|
})
|
|
340
340
|
})
|
|
341
341
|
|
|
342
|
+
test('query builder: preserves null placement in window ordering', async () => {
|
|
343
|
+
await execute({
|
|
344
|
+
query: async wrapper => {
|
|
345
|
+
const qb = wrapper
|
|
346
|
+
.selectBuilder()
|
|
347
|
+
.select(expr =>
|
|
348
|
+
expr.window(window =>
|
|
349
|
+
window
|
|
350
|
+
.rowNumber()
|
|
351
|
+
.orderBy(['foo', 'first'], 'asc nulls first')
|
|
352
|
+
.orderBy(['foo', 'second'], 'desc nulls last')
|
|
353
|
+
)
|
|
354
|
+
)
|
|
355
|
+
|
|
356
|
+
await qb.getResult(wrapper)
|
|
357
|
+
},
|
|
358
|
+
sql: SQL`select row_number() over(order by "foo"."first" asc nulls first, "foo"."second" desc nulls last)`,
|
|
359
|
+
parameters: [],
|
|
360
|
+
})
|
|
361
|
+
})
|
|
362
|
+
|
|
342
363
|
test('query builder: applies limit by group', async () => {
|
|
343
364
|
await execute({
|
|
344
365
|
query: async wrapper => {
|
|
@@ -360,7 +381,7 @@ test('query builder: applies limit by group', async () => {
|
|
|
360
381
|
(select "foo"."bar",
|
|
361
382
|
row_number() over(partition by "foo"."lorem" order by "foo"."ipsum" asc) as "rowNumber_"
|
|
362
383
|
from "public"."foo" order by "foo"."ipsum" asc)
|
|
363
|
-
select "data".* from "data" where "data"."rowNumber_" > ? and "data"."rowNumber_" <=
|
|
384
|
+
select "data".* from "data" where "data"."rowNumber_" > ? and "data"."rowNumber_" <= ? order by "data"."rowNumber_" asc`,
|
|
364
385
|
parameters: [1, 4],
|
|
365
386
|
})
|
|
366
387
|
})
|