在 PostgreSQL 的读提交隔离级别下使用事务进行读查询是否有好处?

问题描述 投票:0回答:1

我将 Prisma 与 PostgreSQL 结合使用。当我读到 PostgreSQL 中的事务隔离时,我想知道我使用的事务是否没有任何好处,或者我是否正确理解了这个主题。

async getProductCounts(categoryIds: string[]): Promise<any> {
  const stats = await this.prisma.$transaction(async (tx) => {
    const productsWithPrice = await tx.product.findMany({
      where: {
        categoryId: {
          in: categoryIds,
        },
        price: {
          not: null,
        },
      },
    });

    const productsWithoutPrice = await tx.product.findMany({
      where: {
        categoryId: {
          in: categoryIds,
        },
        price: null,
      },
    });

    return {
      productsWithPrice,
      productsWithoutPrice,
    };
  });

  return stats;
}

考虑到使用了 Read Comlated 隔离级别,将这些只读 findMany 操作包装在事务中是否会带来任何好处?

我知道读提交无论如何都会使 2 个读查询看到不同的快照,那么为什么要在这里使用事务呢?

我问这个是为了更好地理解 PostgreSQL 中的事务主题。

如果第二个查询是更新,这会有什么不同吗?谢谢您的回答。

postgresql select transactions isolation-level acid
1个回答
0
投票

没有充分的理由将两个只读语句放在读已提交隔离级别上的单个事务中。

如果只有第二条语句修改数据,仍然没有充分的理由。

© www.soinside.com 2019 - 2024. All rights reserved.