Skip to main content

管理 Prisma ORM 环境变量和设置

环境变量是存储在计算机本地环境中的字符串数据的键值对。具体详情请参阅我们的 环境变量参考文档

¥An environment variable is a key value pair of string data that is stored on your machine's local environment. Refer to our Environment variables reference documentation for specific details.

通常变量的名称是大写的,然后是等号,然后是变量的值:

¥Typically the name of the variable is uppercase, this is then followed by an equals sign then the value of the variable:

MY_VALUE=prisma

环境变量属于进程正在运行的环境。任何程序都可以读取和创建这些环境变量。它们是存储简单信息的廉价而有效的方式。

¥The environment variable belongs to the environment where a process is running.Any program can read and create these environment variables. They are a cheap and effective way to store simple information.

提示

使用 Prisma ORM v6.4.0,我们将 prisma.config.ts 文件发布到 Early Access。此文件允许你以更灵活的方式管理环境变量和设置。

¥With Prisma ORM v6.4.0, we released the prisma.config.ts file into Early Access. This file allows you to manage your environment variables and settings in a more flexible way.

有关 查看我们的参考 的更多信息,请参考 分享你的反馈,也别忘了在我们的 GitHub 讨论中与 分享你的反馈 联系!

¥View our reference for more information and don't forget to share your feedback in our GitHub discussions!

Prisma ORM 如何使用环境变量

¥How Prisma ORM can use environment variables

Prisma ORM 始终从系统环境中读取环境变量。

¥Prisma ORM always reads environment variables from the system's environment.

当你使用 prisma init 在项目中初始化 Prisma ORM 时,它会创建一个方便的 .env 文件,供你将 connection url 设置为环境变量。当你使用 Prisma CLI 或 Prisma Client 时,.env 文件内容及其中定义的变量将添加到 process.env object 中,Prisma ORM 可以在其中读取并使用它。

¥When you initialize Prisma ORM in your project with prisma init, it creates a convenience .env file for you to set your connection url as an environment variable. When you use Prisma CLI or Prisma Client, the .env file content and the variables defined in it are added to the process.env object, where Prisma ORM can read it and use it.

使用 .env 文件

¥Using an .env file

警告

不要将 .env 文件提交到版本控制中!

¥Do not commit your .env files into version control!

Prisma CLI 按顺序在以下位置查找 .env 文件:

¥The Prisma CLI looks for .env files, in order, in the following locations:

  1. 在项目的根文件夹中 (./.env)

    ¥In the root folder of your project (./.env)

  2. 来自与 --schema 参数指定的架构相同的文件夹

    ¥From the same folder as the schema specified by the --schema argument

  3. 与从 "prisma": {"schema": "/path/to/schema.prisma"} 中获取的架构位于 package.json 中的同一文件夹中

    ¥From the same folder as the schema taken from "prisma": {"schema": "/path/to/schema.prisma"} in package.json

  4. ./prisma 文件夹

    ¥From the ./prisma folder

如果 .env 文件位于步骤 1 中,但其他冲突的 .env 变量位于步骤 2 中。* 4. CLI 会抛出错误。例如,如果你在两个不同的 .env 文件中指定 DATABASE_URL 变量,你将收到以下错误:

¥If a .env file is located in step 1., but additional, clashing .env variables are located in steps 2. - 4., the CLI will throw an error. For example, if you specify a DATABASE_URL variable in two different .env files, you will get the following error:

Error: There is a conflict between env vars in .env and prisma/.env
Conflicting env vars:
DATABASE_URL

We suggest to move the contents of prisma/.env to .env to consolidate your env vars.

下表描述了 Prisma CLI 在何处查找 .env 文件:

¥The following table describes where the Prisma CLI looks for the .env file:

命令模式位置按顺序检查了 .env 个文件位置
prisma [command]./prisma/schema.prisma./.env
./prisma/.env
prisma [command] --schema=./a/b/schema.prisma./a/b/schema.prisma./.env
./a/b/.env
./prisma/.env
prisma [command]"prisma": {"schema": "/path/to/schema.prisma"}.env
./path/to/schema/.env
./prisma/.env
prisma [command]无架构(例如,在空目录中运行 prisma db pull 时)./.env
./prisma/.env

运行 Prisma CLI 命令时,将自动加载该 .env 文件中定义的任何环境变量。

¥Any environment variables defined in that .env file will automatically be loaded when running a Prisma CLI command.

信息

想要使用多个 .env 文件?有关如何在应用中设置和使用多个 .env 文件的信息,请参阅 使用多个 .env 文件

¥Looking to use more than one .env file? See Using multiple .env files for information on how to setup and use multiple .env files in your application.

有关 如果在两个地方定义环境变量会发生什么 的信息,请参阅 dotenv 文档。

¥Refer to the dotenv documentation for information about what happens if an environment variable is defined in two places.

使用 .env 文件扩展变量

¥Expanding variables with .env files

存储在 .env 文件中的变量可以使用 dotenv-expand 指定的格式进行扩展。

¥Variables stored in .env files can be expanded using the format specified by dotenv-expand.

.env
DATABASE_URL=postgresql://test:test@localhost:5432/test
DATABASE_URL_WITH_SCHEMA=${DATABASE_URL}?schema=public

此外,你可以在扩展中使用在 .env 文件之外设置的环境变量。例如,在 Heroku 或类似 PaaS 上设置的数据库 URL:

¥Additionally, you can use environment variables in the expansion that are set outside of the .env file. For example a database URL that is set on a PaaS like Heroku or similar:

# environment variable already set in the environment of the system
export DATABASE_URL=postgresql://test:test@localhost:5432/test
.env
DATABASE_URL_WITH_SCHEMA=${DATABASE_URL}?schema=foo

这将使环境变量 DATABASE_URL_WITH_SCHEMA 和值 postgresql://test:test@localhost:5432/test?schema=foo 可用于 Prisma ORM。

¥This will make the environment variable DATABASE_URL_WITH_SCHEMA with value postgresql://test:test@localhost:5432/test?schema=foo available for Prisma ORM.

在代码中使用环境变量

¥Using environment variables in your code

如果你希望在运行时评估环境变量,则需要在应用代码中手动加载它们(例如,使用 dotenv):

¥If you want environment variables to be evaluated at runtime, you need to load them manually in your application code (for example, by using dotenv):

import * as dotenv from 'dotenv'

dotenv.config() // Load the environment variables
console.log(`The connection URL is ${process.env.DATABASE_URL}`)

如果你对环境变量使用自定义文件名,则可以将 dotenv 配置为使用该文件名:

¥If you are using a custom file name for your environment variables, you can configure dotenv to use that filename:

import * as dotenv from 'dotenv'

var envFile = path.resolve(join(__dirname, "myenv.env"))
dotenv.config({path: envFile}) // Load the environment variables
console.log(`The connection URL is ${process.env.DATABASE_URL}`)

如果你需要跨环境文件进行变量扩展,你还可以使用 dotenv-expand

¥If you need variable expansion across environment files, you can additionally use dotenv-expand:

import * as dotenv from 'dotenv'
const dotenvExpand = require('dotenv-expand')

var envFile = path.resolve(join(__dirname, "myenv.env"))
var mySqlEnv = dotenv.config({path: envFile})
dotenvExpand.expand(mySqlEnv)

如果你使用多个 .env 文件,你可以根据你正在运行的环境在项目的代码中引用环境文件。

¥If you are using multiple .env files, you can refernce an environment file in your project's code depending on the environment you are running in.

import { config } from 'dotenv'

const envFile = process.env.NODE_ENV === 'development' ? '.env.development' : '.env.production'
config({ path: envFile })

手动设置环境变量

¥Manually set environment variables

由于 Prisma ORM 在查找环境变量时从系统环境中读取,因此可以完全跳过使用 .env 并在本地系统上手动创建它们。

¥Because Prisma ORM reads from the system's environment when looking for environment variables, it's possible to skip using .env completely and create them manually on your local system.

信息

以下示例将使用设置 DATABASE_URL 环境变量,该变量常用于数据库连接 URL。

¥The following examples will use setting the DATABASE_URL environment variable which is often used for the database connection URL.

在 Mac/Linux 系统上手动设置环境变量

¥Manually set an environment variable on a Mac/Linux system

从 Unix 计算机 (Mac/Linux) 上的终端,将变量导出为键值对。

¥From a terminal on a Unix machine (Mac/Linux), you export the variable as a key value pair.

export DATABASE_URL=postgresql://test:test@localhost:5432/test?schema=public

然后使用 printenv 检查是否已成功设置:

¥Then check that it has been successfully set using printenv:

printenv DATABASE_URL
Show CLI results
postgresql://test:test@localhost:5432/test?schema=public

在 Windows 系统上手动设置环境变量

¥Manually set an environment variable on a Windows system

以下示例说明如何根据你的偏好使用命令提示符 (cmd.exe) 和 PowerShell 设置环境变量(针对当前用户)。

¥The following examples illustrate how to set the environment variable (for the current user) using both Command Prompt (cmd.exe) and PowerShell, depending on your preference.

set DATABASE_URL="postgresql://test:test@localhost:5432/test?schema=public"

然后检查是否设置成功:

¥Then check that it has been successfully set:

set DATABASE_URL

使用多个 .env 文件

¥Using multiple .env files

如果你在单个 .env 文件中存储每个环境的不同连接 URL,则存在生产数据库可能被删除的风险。

¥There is a risk that your production database could be deleted if you store different connection URLs to each of your environments within a single .env file.

一种解决方案是拥有多个 .env 文件,每个文件代表不同的环境。实际上,这意味着你为每个环境创建一个文件:

¥One solution is to have multiple .env files which each represent different environments. In practice, this means you create a file for each of your environments:

  • .env.development

  • .env.sample

然后使用像 dotenv-cli 这样的包,你可以为你正在工作的环境加载正确的连接 URL。

¥Then using a package like dotenv-cli, you can load the correct connection URL for the environment you are working in.

信息

出于我们的目的,假设你在开发应用时使用专用的开发数据库。

¥For our purposes, it is assumed you have a dedicated development database that you use while developing your application.

  1. .env 文件重命名为 .env.development

    ¥Rename your .env file to .env.development

.env.development
DATABASE_URL="postgresql://prisma:prisma@localhost:5433/dev"
  1. 创建一个新的 .env.sample 文件并将数据库名称更改为 sample(或你喜欢的名称)

    ¥Create a new .env.sample file and change the database name to sample (or your preferred name)

.env.sample
DATABASE_URL="postgresql://prisma:prisma@localhost:5433/sample"
  1. 安装 dotenv-cli

    ¥Install dotenv-cli

为了让 Prisma ORM 和 Jest 知道要使用哪个 .env 文件,请更改 package.json 脚本以包含并调用 dotenv 包,并根据你正在运行的命令以及你希望它们在哪个环境中运行来指定要使用的文件。

¥In order for Prisma ORM and Jest to know which .env file to use, alter your package.json scripts to include and call the dotenv package and specify which file to use depending on what commands you are running and in which environment you want them to run.

信息

任何运行测试和迁移的顶层脚本都需要在其前面添加 dotenv 命令。这可确保 .env.sample 中的环境变量传递给所有命令,包括 Jest。

¥Any top-level script that is running the tests and migrations needs the dotenv command before it. This makes sure that the env variables from .env.sample are passed to all commands, including Jest.

在不同环境中运行迁移

¥Running migrations on different environments

你可以使用 dotenv-cli 包指定 Prisma ORM 在运行迁移时应使用哪个环境文件。

¥You can use the dotenv-cli package to specify which environment file Prisma ORM should use when running a migration.

以下脚本使用 dotenv-cli.env.sample 环境文件(包含 DATABASE_URL 连接字符串)传递给 Prisma ORM 迁移脚本。

¥The below script uses dotenv-cli to pass the .env.sample environment file (which holds a DATABASE_URL connection string) to the Prisma ORM migration script.

迁移脚本

¥Migration script

package.json
  "scripts": {
"migrate:postgres": "dotenv -e .env.sample -- npx prisma migrate deploy",
},

在不同环境下运行测试

¥Running tests on different environments

运行测试时,我们建议你 模拟 Prisma 客户端。为此,你需要告诉 Jest 在运行测试时应使用哪个环境。

¥When running tests, we advise you to mock Prisma Client. In doing so, you need to tell Jest which environment it should use when running its tests.

默认情况下,Prisma Client 将使用位于项目根目录的默认 .env 文件中指定的环境。

¥By default, Prisma Client will use the environment specified in the default .env file located at the project's root.

如果你创建了单独的 .env.sample 文件来指定测试数据库,则需要将此环境传递给 Jest。

¥If you have created a separate .env.sample file to specify your testing database, then this environment will need to be passed to Jest.

下面的脚本使用 dotenv-cli.env.sample 环境文件(包含 DATABASE_URL 连接字符串)传递给 Jest。

¥The below script uses dotenv-cli to pass the .env.sample environment file (which holds a DATABASE_URL connection string) to Jest.

package.json
  "scripts": {
"test": "dotenv -e .env.sample -- jest -i"
},