简体   繁体   English

如何使用 Prisma 在行数条件下为 Postgres 插入 SQL?

[英]How to do SQL insert for Postgres using Prisma with condition on count of rows?

I am trying to insert a row into database provided that - number of rows satisfying some condition already in the table is less than certain threshold, say 10. For example, in below model, I don't want to have a project to have more than 10 users;我正在尝试在数据库中插入一行,前提是 - 表中已经满足某些条件的行数小于某个阈值,例如 10。例如,在 model 以下,我不想让项目拥有更多超过 10 个用户; so count(projectId) should be less than 10:所以count(projectId)应该小于 10:

model User {
  id            BigInt      @id @default(autoincrement())

  firstName     String      @map("first_name")
  lastName      String      @map("last_name")
  email         String      @unique

  password      String
  passwordHash  String      @map("password_hash")

  createdAt     DateTime    @db.Timestamptz() @default(now()) @map("created_at")
  updatedAt     DateTime    @db.Timestamptz() @updatedAt @map("updated_at")

  project       Project     @relation(fields: [projectId], references: [id])
  projectId     BigInt?     @map("project_id")

  @@map("app_user")
}

model Project {
  id            BigInt    @id @default(autoincrement())
  name          String

  users         User[]

  @@map("project")
}

In general SQL world, I would rely on transaction with Optimistic Concurrency Control and then attempt the insert only after reading the count of rows matching project_id .在一般 SQL 世界中,我会依赖具有乐观并发控制的事务,然后仅在读取与project_id匹配的行数后尝试插入。 Since, Prisma doesn't provide traditional long running transaction, I am stuck.由于 Prisma 不提供传统的长时间运行的事务,我被卡住了。 I cannot just simply run the count query first and then do the insert since it won't be atomic in nature.我不能只是简单地先运行计数查询然后再进行插入,因为它本质上不是原子的。

How to handle this scenario with Prisma?如何使用 Prisma 处理这种情况?

You can do this in two ways:您可以通过两种方式做到这一点:

  1. Add a version field in your model and perform Optimistic Concurrency Control in your application logic as shown here .在您的 model 中添加一个version字段,并在您的应用程序逻辑中执行乐观并发控制,如此处所示

  2. Use Prisma's raw query mechanism to run a native transaction.使用 Prisma 的原始查询机制来运行本机事务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM