-
Notifications
You must be signed in to change notification settings - Fork 253
/
transaction.test.ts
204 lines (184 loc) · 5.38 KB
/
transaction.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import { CompiledQuery, Transaction } from '../../../'
import {
DIALECTS,
clearDatabase,
destroyTest,
initTest,
TestContext,
expect,
Database,
insertDefaultDataSet,
} from './test-setup.js'
for (const dialect of DIALECTS) {
describe(`${dialect}: transaction`, () => {
let ctx: TestContext
let executedQueries: CompiledQuery[] = []
before(async function () {
ctx = await initTest(this, dialect, (event) => {
if (event.level === 'query') {
executedQueries.push(event.query)
}
})
})
beforeEach(async () => {
await insertDefaultDataSet(ctx)
executedQueries = []
})
afterEach(async () => {
await clearDatabase(ctx)
})
after(async () => {
await destroyTest(ctx)
})
if (dialect !== 'sqlite') {
it('should set the transaction isolation level', async () => {
await ctx.db
.transaction()
.setIsolationLevel('serializable')
.execute(async (trx) => {
await trx
.insertInto('person')
.values({
first_name: 'Foo',
last_name: 'Barson',
gender: 'male',
})
.execute()
})
if (dialect == 'postgres') {
expect(
executedQueries.map((it) => ({
sql: it.sql,
parameters: it.parameters,
}))
).to.eql([
{
sql: 'start transaction isolation level serializable',
parameters: [],
},
{
sql: 'insert into "person" ("first_name", "last_name", "gender") values ($1, $2, $3)',
parameters: ['Foo', 'Barson', 'male'],
},
{ sql: 'commit', parameters: [] },
])
} else if (dialect === 'mysql') {
expect(
executedQueries.map((it) => ({
sql: it.sql,
parameters: it.parameters,
}))
).to.eql([
{
sql: 'set transaction isolation level serializable',
parameters: [],
},
{
sql: 'begin',
parameters: [],
},
{
sql: 'insert into `person` (`first_name`, `last_name`, `gender`) values (?, ?, ?)',
parameters: ['Foo', 'Barson', 'male'],
},
{ sql: 'commit', parameters: [] },
])
}
})
}
if (dialect === 'postgres') {
it('should be able to start a transaction with a single connection', async () => {
const result = await ctx.db.connection().execute((db) => {
return db.transaction().execute((trx) => {
return trx
.insertInto('person')
.values({
first_name: 'Foo',
last_name: 'Barson',
gender: 'male',
})
.returning('first_name')
.executeTakeFirstOrThrow()
})
})
expect(result.first_name).to.equal('Foo')
})
}
it('should run multiple transactions in parallel', async () => {
const threads = Array.from({ length: 100 }).map((_, index) => ({
id: 1000000 + index + 1,
fails: Math.random() < 0.5,
}))
const results = await Promise.allSettled(
threads.map((thread) => executeThread(thread.id, thread.fails))
)
for (let i = 0; i < threads.length; ++i) {
const [personExists, petExists] = await Promise.all([
doesPersonExists(threads[i].id),
doesPetExists(threads[i].id),
])
if (threads[i].fails) {
expect(personExists).to.equal(false)
expect(petExists).to.equal(false)
expect(results[i].status === 'rejected')
} else {
expect(personExists).to.equal(true)
expect(petExists).to.equal(true)
expect(results[i].status === 'fulfilled')
}
}
async function executeThread(id: number, fails: boolean): Promise<void> {
await ctx.db.transaction().execute(async (trx) => {
await insertPerson(trx, id)
await insertPet(trx, id)
if (fails) {
throw new Error()
}
})
}
})
async function insertPet(
trx: Transaction<Database>,
ownerId: number
): Promise<void> {
await trx
.insertInto('pet')
.values({
name: `Pet of ${ownerId}`,
owner_id: ownerId,
species: 'cat',
})
.execute()
}
async function insertPerson(
trx: Transaction<Database>,
id: number
): Promise<void> {
await trx
.insertInto('person')
.values({
id: id,
first_name: `Person ${id}`,
last_name: null,
gender: 'other',
})
.execute()
}
async function doesPersonExists(id: number): Promise<boolean> {
return !!(await ctx.db
.selectFrom('person')
.select('id')
.where('id', '=', id)
.where('first_name', '=', `Person ${id}`)
.executeTakeFirst())
}
async function doesPetExists(ownerId: number): Promise<boolean> {
return !!(await ctx.db
.selectFrom('pet')
.select('id')
.where('owner_id', '=', ownerId)
.where('name', '=', `Pet of ${ownerId}`)
.executeTakeFirst())
}
})
}