最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - Is it okay to use neon-serverless without Pool or Client despite performing transaction queries with Drizzle ORM? -

programmeradmin4浏览0评论

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:

  1. Should I be using Pool/Client instead of the current setup with drizzle-orm/neon-serverless?
  2. Is my current approach safe for concurrent reservations?
  3. Are there any potential connection handling issues I should be aware of?

Any guidance would be appreciated!

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论