-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtestConcurrentWrites.ts
92 lines (76 loc) · 2.04 KB
/
testConcurrentWrites.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
import { PrismaClient } from "@prisma/client";
import { range } from "lodash";
const prisma = new PrismaClient({
log: ["error", "info", "query", "warn"],
});
type TransactionPrisma = Omit<
PrismaClient,
"$connect" | "$disconnect" | "$on" | "$transaction" | "$use"
>;
// A `main` function so that you can use async/await
async function main() {
const createdUser = await prisma.user.upsert({
where: {
email: "[email protected]",
},
create: {
email: "[email protected]",
name: "user-1",
},
update: {
id: 1,
},
});
console.log("createdUser", createdUser);
// Set this value to the number of parallel transactions
const CONCURRENCY = 10;
const WITH_LOCK = true;
const ADD_DELAY = true;
const promises = range(0, CONCURRENCY).map(() =>
prisma.$transaction(
async (transactionPrisma: TransactionPrisma) => {
console.log("started transaction");
if (WITH_LOCK) {
await transactionPrisma.$queryRaw`SELECT id from "User" where email = '[email protected]' FOR UPDATE`;
}
const user = await transactionPrisma.user.findUnique({
rejectOnNotFound: true,
where: {
email: "[email protected]",
},
});
// brief delay
if (ADD_DELAY) {
await new Promise((r) => setTimeout(r, 100));
}
const updatedUser = await transactionPrisma.user.update({
where: {
email: "[email protected]",
},
data: {
id: user.id + 1,
},
});
console.log("updated user id", updatedUser.id);
return updatedUser;
},
{ timeout: 60000 }
)
);
const result = await Promise.allSettled(promises);
console.log("result", result);
const finalUser = await prisma.user.findUnique({
rejectOnNotFound: true,
where: {
email: "[email protected]",
},
});
console.log("finalUser id is", finalUser.id);
}
main()
.catch((e) => {
throw e;
})
.finally(async () => {
await prisma.$disconnect();
});