NextJS开发:Prisma数据库事务处理

Prisma是一个开源的ORM库,用于在Node.js和TypeScript中访问数据库。它可以轻松地将数据库模式转换为GraphQL API,并提供查询和变更解析器。Prisma支持多个数据库,包括PostgreSQL,MySQL,SQLite和SQL Server。Prisma使用数据模型定义和可重用模块的概念来帮助开发者快速建设可扩展、可维护的应用程序。它还提供了数据实时更新和订阅的功能,使得应用程序更加响应和动态。Prisma提供了多种开启事务处理的编码方式,适用于不同场景。

1、$transaction api方式处理事务

typescript 复制代码
const deleteChapter = prisma.chapter.delete({
  where: {
    docId: docId,
    chapterId: chapterId,
  },
})

const deleteChapterContent =  prisma.chapterContent.deleteMany({
  where: {
    chapterId: chapterId,
  },
})

await prisma.$transaction([deleteChapter, deleteChapterContent])

适用于:后一条数据库,不需要前一条的返回的结果,甚至变换前后执行顺序也不影响最终结果的场景。关联保存场景,先保存主表,再用主表的自增主键来继续保存子表数据显然就不适用这种适用于嵌套事务(推荐)或交互式事务。

2、嵌套事务

一对一关联

typescript 复制代码
model Chapter {
  @@map("d_chapter")
  chapterId         BigInt @id @default(autoincrement()) @map("chapter_id")
  chapterName       String @db.VarChar(128) @map("chapter_name")
  chapterContent    ChapterContent?
}

model ChapterContent {
  @@map("d_chapter_content")
  chapterId         BigInt @id @map("chapter_id")
  content           String? @db.Text
  chapter           Chapter @relation(fields: [chapterId], references: [chapterId])
}

嵌套事务操作数据保存

typescript 复制代码
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
let chapter = await prisma.chapter.create({
  data: {
    chapterName: "test",
    content: {
      create: {
        content: '', createAt: DateUtils.now()
      }
    }
  },
})

一对多关联

typescript 复制代码
let chapter = await prisma.account.create({
  data: {
    userName: "test",
    articles: 
      create: [
        { content: '', createAt: DateUtils.now() },
        { content: '', createAt: DateUtils.now() }
      ]
    }
  },
})

3、交互式事务

适用于事务期间有逻辑判断是否执行后续事务分支的场景,为了支持这种用例和更多的用例,你可以通过在你的 Prisma Schema 的生成器中添加interactiveTransactions来启用交互式事务

typescript 复制代码
generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["interactiveTransactions"]
}
typescript 复制代码
import { Seat } from 'prisma'
const userEmail = 'alice@prisma.io'
const movieName = 'HiddenFigures'

// 开始事务
const seat: Seat = await prisma.$transaction(async (prisma) => {
  // 找到一个可用座位
  const availableSeat = await prisma.seat.findFirst({
    where: {
      claimedBy: null,
      movie: {
        name: movieName,
      },
    },
  })

  // 如果座位不存在抛异常
  if (!availableSeat) {
    // 这将会滚事务
    throw new Error(`Oh no! ${movieName} is all booked.`)
  }

  // 认领座位,提交事务,返回结果
  return prisma.seat.update({
    data: {
      claimedBy: userEmail,
    },
    where: {
      id: availableSeat.id,
    },
  })
})
相关推荐
Q_Q5110082852 小时前
python+django/flask的眼科患者随访管理系统 AI智能模型
spring boot·python·django·flask·node.js·php
Q_Q5110082853 小时前
python+django/flask的在线学习系统的设计与实现 积分兑换礼物
spring boot·python·django·flask·node.js·php
学习3人组4 小时前
Node.js 登录接口实现
node.js
Q_Q5110082854 小时前
python+django/flask的车辆尾气检测排放系统-可视化大屏展示
spring boot·python·django·flask·node.js·php
学习3人组5 小时前
Node.js 网站服务器开发
运维·服务器·node.js
Q_Q19632884757 小时前
python+django/flask基于Echarts+Python的图书零售监测系统设计与实现(带大屏)
spring boot·python·django·flask·node.js·php
粥里有勺糖7 小时前
视野修炼-技术周刊第126期 | TypeScript #1
前端·node.js·github
玖釉-8 小时前
解决PowerShell执行策略导致的npm脚本无法运行问题
前端·npm·node.js
Q_Q51100828511 小时前
python+django/flask的莱元元电商数据分析系统_电商销量预测
spring boot·python·django·flask·node.js·php
Q_Q196328847513 小时前
python+django/flask基于协同过滤算法的理财产品推荐系统
spring boot·python·django·flask·node.js·php