I read in the Neon docs that if I'm using transactions, I should use Pool or Client. And that Pool or Client objects must be connected, used and closed within a single request handler.
I'm using neon-serverless with drizzle-orm without using Pool or Client. Here's my current implementation:
Database configuration (db.ts)
import { drizzle } from 'drizzle-orm/neon-serverless';
import ws from 'ws';
export const db = drizzle({
connection: process.env.DATABASE_URL!,
ws: ws,
});
Transaction code (reserve/page.tsx)
// ...
try {
await db.transaction(async (tx) => {
// Find an available dining table
const availableTable = await tx
.select()
.from(diningTables)
.where(
and(
// Ensure the table has sufficient capacity
gte(diningTables.capacity, Number(guests)),
// Ensure no overlapping reservations exist for this table
not(
exists(
tx
.select()
.from(reservations)
.where(
and(
eq(reservations.diningTableId, diningTables.id),
eq(reservations.reservationDate, date),
lt(reservations.startTime, endTime),
gt(reservations.endTime, time)
)
)
)
)
)
)
.limit(1)
.execute()
.then((res) => res[0]);
if (!availableTable) {
throw new Error('No available dining table.');
}
// Insert the reservation
await tx
.insert(reservations)
.values({
diningTableId: availableTable.id,
name: name,
email: email,
notes: notes,
reservationDate: date,
startTime: time,
endTime: endTime
})
.execute();
});
} catch (error: unknown) {
if (error instanceof Error) {
console.error('Error creating reservation:', error.message);
} else {
console.error('An unexpected error occurred.');
}
return;
}
//...
See the full code here: .tsx#L39
The code works as expected - it successfully handles table reservations with proper transaction isolation (finding an available table and creating the reservation atomically). However, I want to ensure this is the correct way to implement transactions with drizzle-orm and neon-serverless.
Specific questions:
- Should I be using Pool/Client instead of the current setup with
drizzle-orm/neon-serverless
? - Is my current approach safe for concurrent reservations?
- Are there any potential connection handling issues I should be aware of?
Any guidance would be appreciated!