Skip to main content

如何从 Sequelize 迁移到 Prisma ORM

15 min

介绍

¥Introduction

本指南将向你展示如何将应用从 Sequelize 迁移到 Prisma ORM。我们将使用 Sequelize Express 示例 的扩展版本作为 示例项目 来演示迁移步骤。

¥This guide shows you how to migrate your application from Sequelize to Prisma ORM. We'll use an extended version of the Sequelize Express example as a sample project to demonstrate the migration steps.

本迁移指南以 PostgreSQL 为示例数据库,但同样适用于任何其他 Prisma ORM 支持 关系数据库。你可以在 Prisma ORM 与 Sequelize 页面上了解 Prisma ORM 与 Sequelize 的比较。

¥This migration guide uses PostgreSQL as the example database, but it equally applies to any other relational database that's supported by Prisma ORM. You can learn how Prisma ORM compares to Sequelize on the Prisma ORM vs Sequelize page.

先决条件

¥Prerequisites

在开始本指南之前,请确保你已准备好:

¥Before starting this guide, make sure you have:

  • 一个要迁移的 Sequelize 项目

    ¥A Sequelize project you want to migrate

  • 已安装 Node.js(版本 18 或更高版本)

    ¥Node.js installed (version 18 or higher)

  • PostgreSQL 或其他受支持的数据库

    ¥PostgreSQL or another supported database

  • 基本了解 Sequelize 和 Express.js

    ¥Basic familiarity with Sequelize and Express.js

1. 准备迁移

¥ Prepare for migration

1.1.了解迁移过程

¥1.1. Understand the migration process

无论你构建的是哪种应用或 API 层,从 Sequelize 迁移到 Prisma ORM 的步骤始终相同:

¥The steps for migrating from Sequelize to Prisma ORM are always the same, no matter what kind of application or API layer you're building:

  1. 安装 Prisma CLI

    ¥Install the Prisma CLI

  2. 检查你的数据库

    ¥Introspect your database

  3. 创建基线迁移

    ¥Create a baseline migration

  4. 安装 Prisma 客户端

    ¥Install Prisma Client

  5. 逐步用 Prisma 客户端替换 Sequelize 查询

    ¥Gradually replace your Sequelize queries with Prisma Client

无论你是在构建 REST API(例如,使用 Express、Koa 或 NestJS)、GraphQL API(例如,使用 Apollo Server、TypeGraphQL 或 Nexus),还是任何其他使用 Sequelize 进行数据库访问的应用,这些步骤都适用。

¥These steps apply whether you're building a REST API (e.g., with Express, Koa, or NestJS), a GraphQL API (e.g., with Apollo Server, TypeGraphQL, or Nexus), or any other kind of application that uses Sequelize for database access.

1.2.设置 Prisma 配置

¥1.2. Set up Prisma configuration

创建一个新的 Prisma 模式文件:

¥Create a new Prisma schema file:

npx prisma init --output ../generated/prisma

此命令为你创建了一个名为 prisma 的新目录,其中包含以下文件:

¥This command created a new directory called prisma with the following files for you:

  • schema.prisma:指定数据库连接和模型的 Prisma 模式

    ¥schema.prisma: Your Prisma schema that specifies your database connection and models

  • .env:一个 dotenv,用于将数据库连接 URL 配置为环境变量

    ¥.env: A dotenv to configure your database connection URL as an environment variable

Prisma 模式目前如下所示:

¥The Prisma schema currently looks as follows:

prisma/schema.prisma
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

generator client {
provider = "prisma-client-js"
}
提示

如果你使用的是 VS Code,请务必安装 Prisma VS Code 扩展 以获得语法高亮、格式化、自动补齐等更多酷炫功能。

¥If you're using VS Code, be sure to install the Prisma VS Code extension for syntax highlighting, formatting, auto-completion and a lot more cool features.

使用数据库连接字符串更新 .env 文件中的 DATABASE_URL

¥Update the DATABASE_URL in the .env file with your database connection string:

DATABASE_URL="postgresql://USER:PASSWORD@HOST:PORT/DATABASE"

2. 迁移数据库模式

¥ Migrate the database schema

2.1.检查你的数据库

¥2.1. Introspect your database

运行 Prisma 的自省功能,从现有数据库创建 Prisma 模式:

¥Run Prisma's introspection to create the Prisma schema from your existing database:

npx prisma db pull

这将创建一个包含数据库架构的 schema.prisma 文件。

¥This will create a schema.prisma file with your database schema.

2.2.创建基线迁移

¥2.2. Create a baseline migration

要继续使用 Prisma Migrate 来改进你的数据库模式,你需要 数据库的基线

¥To continue using Prisma Migrate to evolve your database schema, you will need to baseline your database.

首先,创建一个 migrations 目录,并在其中添加一个目录,其中包含你用于迁移的首选名称。在此示例中,我们将使用 0_init 作为迁移名称:

¥First, create a migrations directory and add a directory inside with your preferred name for the migration. In this example, we will use 0_init as the migration name:

mkdir -p prisma/migrations/0_init

接下来,使用 prisma migrate diff 生成迁移文件。使用以下参数:

¥Next, generate the migration file with prisma migrate diff. Use the following arguments:

  • --from-empty:假设你要迁移的数据模型为空

    ¥--from-empty: assumes the data model you're migrating from is empty

  • --to-schema-datamodel:使用 datasource 块中的 URL 获取当前数据库状态

    ¥--to-schema-datamodel: the current database state using the URL in the datasource block

  • --script:输出 SQL 脚本

    ¥--script: output a SQL script

npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql
npx prisma migrate resolve --applied 0_init

该命令将通过将 0_init 添加到 _prisma_migrations 表来将其标记为已应用。

¥The command will mark 0_init as applied by adding it to the _prisma_migrations table.

你现在已经有了当前数据库架构的基线。要对数据库架构进行进一步更改,你可以更新 Prisma 架构并使用 prisma migrate dev 将更改应用到数据库。

¥You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use prisma migrate dev to apply the changes to your database.

3. 更新你的应用代码

¥ Update your application code

3.1.安装 Prisma 客户端

¥3.1. Install Prisma Client

下一步,你可以在项目中安装 Prisma 客户端,以便开始替换项目中当前使用 Sequelize 进行的数据库查询:

¥As a next step, you can install Prisma Client in your project so that you can start replacing the database queries in your project that are currently made with Sequelize:

npm install @prisma/client

安装 Prisma 客户端后,你可以生成 Prisma 客户端代码:

¥After installing Prisma Client, you can generate the Prisma Client code:

npx prisma generate

3.2.替换 Sequelize 查询

¥3.2. Replace Sequelize queries

在本节中,我们将基于示例 REST API 项目中的示例路由,展示一些从 Sequelize 迁移到 Prisma 客户端的示例查询。要全面了解 Prisma 客户端 API 与 Sequelize 的区别,请查看 API 比较 页面。

¥In this section, we'll show a few sample queries that are being migrated from Sequelize to Prisma Client based on the example routes from the sample REST API project. For a comprehensive overview of how the Prisma Client API differs from Sequelize, check out the API comparison page.

// Find one
const user = await User.findOne({
where: { id: 1 }
});

// Create
const user = await User.create({
email: 'alice@prisma.io',
name: 'Alice'
});

// Update
await User.update({ name: 'New name' }, {
where: { id: 1 }
});

// Delete
await User.destroy({
where: { id: 1 }
});

3.3.更新你的控制器

¥3.3. Update your controllers

更新 Express 控制器以使用 Prisma 客户端。例如,以下是如何更新用户控制器:

¥Update your Express controllers to use Prisma Client. For example, here's how to update a user controller:

import { prisma } from '../client'

export class UserController {
async create(req: Request, res: Response) {
const { email, name } = req.body

const result = await prisma.user.create({
data: {
email,
name,
},
})

return res.json(result)
}
}

下一步

¥Next steps

现在你已经迁移到 Prisma ORM,你可以:

¥Now that you've migrated to Prisma ORM, you can:

  • 使用 Prisma 强大的查询 API 添加更复杂的查询

    ¥Add more complex queries using Prisma's powerful query API

  • 设置 Prisma Studio 进行数据库管理

    ¥Set up Prisma Studio for database management

  • 实现数据库监控

    ¥Implement database monitoring

  • 使用 Prisma 的测试实用程序

    ¥Add automated tests using Prisma's testing utilities

更多信息:

¥For more information:


Stay connected with Prisma

Continue your Prisma journey by connecting with our active community. Stay informed, get involved, and collaborate with other developers:

We genuinely value your involvement and look forward to having you as part of our community!