Prisma Config 参考
概述
¥Overview
Prisma 配置文件使用 TypeScript 配置 Prisma CLI,包括 migrate 和 studio 等子命令。
¥The Prisma Config file configures the Prisma CLI, including subcommands like migrate and studio, using TypeScript.
从 Prisma ORM v7 开始,当你运行 prisma init 时,会自动创建一个 prisma.config.ts 文件。数据库连接 URL 现在在此文件中配置,而不是在 schema.prisma 文件中配置。有关设置详情,请参阅 使用环境变量。
¥Starting with Prisma ORM v7, when you run prisma init, a prisma.config.ts file is automatically created. The database connection URL is now configured in this file instead of in the schema.prisma file. See Using environment variables for setup details.
你可以通过以下两种方式之一定义你的配置:
¥You can define your config in either of two ways:
-
使用
defineConfig助手:¥Using the
defineConfighelper:import 'dotenv/config'
import { defineConfig, env } from "prisma/config";
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
seed: 'tsx prisma/seed.ts',
},
datasource: {
url: env("DATABASE_URL")
}
}); -
将 TypeScript 的
satisfies运算符与PrismaConfig类型结合使用:¥Using TypeScript's
satisfiesoperator with thePrismaConfigtype:import 'dotenv/config'
import type { PrismaConfig } from "prisma";
import { env } from "prisma/config";
export default {
schema: "prisma/schema.prisma",
migrations: {
path: "prisma/migrations",
seed: 'tsx prisma/seed.ts',
},
datasource: {
url: env("DATABASE_URL")
}
} satisfies PrismaConfig;
配置界面
¥Configuration interface
以下是 PrismaConfig 类型的简化版本:
¥Here is a simplified version of the PrismaConfig type:
export declare type PrismaConfig = {
// Whether features with an unstable API are enabled.
experimental: {
externalTables: boolean;
},
// The path to the schema file, or path to a folder that shall be recursively searched for *.prisma files.
schema?: string;
// Configuration for Prisma migrations.
migrations?: {
path: string;
seed: string;
initShadowDb: string;
};
// Configuration for the database view entities.
views?: {
path: string;
};
// Configuration for the `typedSql` preview feature.
typedSql?: {
path: string;
};
// Database connection configuration
datasource?: {
url: string;
shadowDatabaseUrl?: string;
}
};
在 Prisma ORM v6.19 及更早版本中,配置界面还包含:
¥In Prisma ORM v6.19 and earlier, the configuration interface also included:
-
experimental.adapter和experimental.studio标志¥
experimental.adapterandexperimental.studioflags -
用于配置驱动程序适配器的
adapter属性¥
adapterproperty for configuring driver adapters -
用于 Prisma Studio 配置的
studio属性¥
studioproperty for Prisma Studio configuration -
用于直接数据库连接的
datasource.directUrl属性¥
datasource.directUrlproperty for direct database connections -
用于选择
classic或js引擎的engine属性¥
engineproperty for choosing betweenclassicandjsengines
这些命令已在 Prisma ORM v7 中移除。有关迁移指南,请参阅下面的各个属性部分。
¥These have been removed in Prisma ORM v7. See the individual property sections below for migration guidance.
支持的文件扩展名
¥Supported file extensions
Prisma 配置文件可以命名为 prisma.config.* 或 .config/prisma.*,并使用扩展名 js、ts、mjs、cjs、mts 或 cts。支持其他扩展,以确保与不同的 TypeScript 编译器设置兼容。
¥Prisma Config files can be named as prisma.config.* or .config/prisma.* with the extensions js, ts, mjs, cjs, mts, or cts. Other extensions are supported to ensure compatibility with different TypeScript compiler settings.
-
对于小型 TypeScript 项目,请使用
prisma.config.ts。¥Use
prisma.config.tsfor small TypeScript projects. -
对于具有多个配置文件的大型 TypeScript 项目(遵循
.config目录提案),请使用.config/prisma.ts。¥Use
.config/prisma.tsfor larger TypeScript projects with multiple configuration files (following the.configdirectory proposal).
选项参考
¥Options reference
schema
配置 Prisma ORM 定位和加载架构文件的方式。可以是文件或文件夹路径。相对路径是相对于 prisma.config.ts 文件位置解析的。有关模式位置选项的更多信息,请参阅 此处。
¥Configures how Prisma ORM locates and loads your schema file(s). Can be a file or folder path. Relative paths are resolved relative to the prisma.config.ts file location. See here for more info about schema location options.
| 属性 | 类型 | 必需的 | 默认 |
|---|---|---|---|
schema | string | 不 | ./prisma/schema.prisma 和 ./schema.prisma |
tables.external 和 enums.external
¥tables.external and enums.external
这些选项声明数据库中由外部管理(而非由 Prisma Migrate 管理)的表和枚举。你仍然可以使用 Prisma 客户端查询它们,但它们将被迁移忽略。
¥These options declare tables and enums in your database that are managed externally (not by Prisma Migrate). You can still query them with Prisma Client, but they will be ignored by migrations.
| 属性 | 类型 | 必需的 | 默认 |
|---|---|---|---|
tables.external | string[] | 不 | [] |
enums.external | string[] | 不 | [] |
示例:
¥Example:
import 'dotenv/config'
import { defineConfig, env } from "prisma/config";
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: env('DATABASE_URL'),
},
experimental: {
externalTables: true,
},
tables: {
external: ["public.users"],
},
enums: {
external: ["public.role"],
},
});
了解更多关于 externalTables 功能在此 的信息。
¥Learn more about the externalTables feature here.
migrations.path
Prisma 存储迁移文件的目录路径,并查找它们。
¥The path to the directory where Prisma should store migration files, and look for them.
| 属性 | 类型 | 必需的 | 默认 |
|---|---|---|---|
migrations.path | string | 不 | none |
migrations.seed
此选项允许你定义一个脚本,Prisma 会在你执行 npx prisma db seed 命令时运行该脚本。该字符串应为可在你的终端中执行的命令,例如使用 node、ts-node 或 tsx。
¥This option allows you to define a script that Prisma runs when you execute the npx prisma db seed command. The string should be a command that can be executed in your terminal, such as with node, ts-node, or tsx.
在 Prisma ORM v7 中,只有显式运行 npx prisma db seed 才会触发初始化。在 Prisma ORM v6 及更早版本中,种子脚本也会在 prisma migrate dev 和 prisma migrate reset 之后自动运行。
¥In Prisma ORM v7, seeding is only triggered explicitly via npx prisma db seed. In Prisma ORM v6 and earlier, the seed script also ran automatically after prisma migrate dev and prisma migrate reset.
| 属性 | 类型 | 必需的 | 默认 |
|---|---|---|---|
migrations.seed | string | 不 | none |
示例:
¥Example:
import 'dotenv/config'
import { defineConfig, env } from "prisma/config";
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
seed: 'tsx db/seed.ts',
},
datasource: {
url: env('DATABASE_URL'),
},
});
migrations.initShadowDb
此选项允许你在创建迁移之前定义 Prisma 在影子数据库上运行的 SQL 语句。在使用 外部管理表 时,此功能非常有用,因为 Prisma 需要了解这些表的结构才能正确生成迁移。
¥This option allows you to define SQL statements that Prisma runs on the shadow database before creating migrations. It is useful when working with external managed tables, as Prisma needs to know about the structure of these tables to correctly generate migrations.
| 属性 | 类型 | 必需的 | 默认 |
|---|---|---|---|
migrations.initShadowDb | string | 不 | none |
示例:
¥Example:
import 'dotenv/config'
import { defineConfig, env } from "prisma/config";
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
initShadowDb: `
CREATE TABLE public.users (id SERIAL PRIMARY KEY);
`,
},
datasource: {
url: env('DATABASE_URL'),
},
experimental: {
externalTables: true,
},
tables: {
external: ["public.users"],
},
});
了解更多关于 externalTables 功能在此 的信息。
¥Learn more about the externalTables feature here.
views.path
Prisma 查找 SQL 视图定义的目录路径。
¥The path to the directory where Prisma should look for the SQL view definitions.
| 属性 | 类型 | 必需的 | 默认 |
|---|---|---|---|
views.path | string | 不 | none |
typedSql.path
Prisma 应在其中查找用于通过 typedSql 生成类型的 SQL 文件的目录路径。
¥The path to the directory where Prisma should look for the SQL files used for generating typings via typedSql.
| 属性 | 类型 | 必需的 | 默认 |
|---|---|---|---|
typedSql.path | string | 不 | none |
experimental
在 Prisma CLI 中启用特定的实验性功能。
¥Enables specific experimental features in the Prisma CLI.
| 属性 | 类型 | 必需的 | 默认 |
|---|---|---|---|
externalTables | boolean | 不 | false |
示例:
¥Example:
import 'dotenv/config'
import { defineConfig, env } from "prisma/config";
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: env('DATABASE_URL'),
},
experimental: {
externalTables: true,
},
});
如果你在未启用实验性标志的情况下使用 externalTables 功能,Prisma 将抛出错误:
¥If you use the externalTables feature without enabling the experimental flag, Prisma will throw an error:
Failed to load config file "~" as a TypeScript/JavaScript module. Error: Error: The `externalTables` configuration requires `experimental.externalTables` to be set to `true`.
在 Prisma ORM v6.19 及更早版本中,experimental 对象还包含 adapter 和 studio 标志。这些命令已在 Prisma ORM v7 中移除。有关详细信息,请参阅 adapter 和 studio 部分。
¥In Prisma ORM v6.19 and earlier, the experimental object also included adapter and studio flags. These have been removed in Prisma ORM v7. See the adapter and studio sections for details.
datasource.url
连接 URL 包括身份验证信息。大多数连接器使用 数据库提供的语法。
¥Connection URL including authentication info. Most connectors use the syntax provided by the database.
在 Prisma ORM v7 中,url 字段在 prisma.config.ts 文件中配置,而不是在 schema.prisma 中的 datasource 代码块 文件中配置。运行 prisma init 时,生成的 schema.prisma 文件不会在 datasource 块中包含 url 属性。
¥In Prisma ORM v7, the url field is configured in prisma.config.ts instead of in the datasource block of your schema.prisma file. When you run prisma init, the generated schema.prisma file will not include a url property in the datasource block.
对于 Prisma ORM v6.19 及更早版本,url 字段保留在 schema.prisma 文件的 datasource 块中。
¥For Prisma ORM v6.19 and earlier, the url field remains in the schema.prisma file's datasource block.
| 属性 | 类型 | 必需的 | 默认 |
|---|---|---|---|
datasource.url | string | 是的 | '' |
示例:
¥Example:
import 'dotenv/config'
import { defineConfig, env } from "prisma/config";
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: env('DATABASE_URL'),
},
});
datasource.shadowDatabaseUrl
Prisma Migrate 使用的影子数据库的连接 URL。允许你使用云托管数据库作为影子数据库。
¥Connection URL to the shadow database used by Prisma Migrate. Allows you to use a cloud-hosted database as the shadow database.
在 Prisma ORM v7 中,shadowDatabaseUrl 字段是在 prisma.config.ts 中配置的,而不是在 schema.prisma 文件的 datasource 代码块中配置的。
¥In Prisma ORM v7, the shadowDatabaseUrl field is configured in prisma.config.ts instead of in the datasource block of your schema.prisma file.
对于 Prisma ORM v6.19 及更早版本,shadowDatabaseUrl 字段保留在 schema.prisma 文件的 datasource 块中。
¥For Prisma ORM v6.19 and earlier, the shadowDatabaseUrl field remains in the schema.prisma file's datasource block.
| 属性 | 类型 | 必需的 | 默认 |
|---|---|---|---|
datasource.shadowDatabaseUrl | string | 不 | '' |
datasource.directUrl(已移除)
¥datasource.directUrl (Removed)
在 Prisma ORM v7 中,datasource.directUrl 属性已被移除,取而代之的是 url 属性 属性。
¥The datasource.directUrl property has been removed in Prisma ORM v7 in favor of the url property.
For Prisma ORM v6.19 and earlier
用于直接连接到数据库的连接 URL。
¥Connection URL for direct connection to the database.
如果你在 url 参数中使用连接池 URL(例如 pgBouncer),则需要直接连接到数据库的 Prisma CLI 命令将使用 directUrl 参数中的 URL。
¥If you use a connection pooler URL in the url argument (for example, pgBouncer), Prisma CLI commands that require a direct connection to the database use the URL in the directUrl argument.
从 5.1.0 版本开始,Prisma Studio 支持 directUrl 属性。使用 Prisma Postgres 数据库时,不需要 directUrl 属性。
¥The directUrl property is supported by Prisma Studio from version 5.1.0 upwards. The directUrl property is not needed when using Prisma Postgres database.
| 属性 | 类型 | 必需的 | 默认 |
|---|---|---|---|
datasource.directUrl | string | 不 | '' |
adapter(已移除)
¥adapter (Removed)
在 Prisma ORM v7 中,adapter 属性已被移除。从 Prisma ORM v7 开始,驱动程序适配器的迁移无需在 prisma.config.ts 中进行额外配置即可自动运行。
¥The adapter property has been removed in Prisma ORM v7. Migrations for driver adapters work automatically without additional configuration in prisma.config.ts as of Prisma ORM v7.
For Prisma ORM v6.19 and earlier
返回 Prisma 驱动程序适配器实例的函数,Prisma CLI 会使用该实例运行迁移。该函数应返回一个可解析为有效 Prisma 驱动程序适配器的 Promise。
¥A function that returns a Prisma driver adapter instance which is used by the Prisma CLI to run migrations. The function should return a Promise that resolves to a valid Prisma driver adapter.
| 属性 | 类型 | 必需的 | 默认 |
|---|---|---|---|
adapter | () => Promise<SqlMigrationAwareDriverAdapterFactory> | 不 | none |
使用 Prisma ORM D1 驱动程序适配器的示例:
¥Example using the Prisma ORM D1 driver adapter:
import path from "node:path";
import type { PrismaConfig } from "prisma";
import { PrismaD1 } from "@prisma/adapter-d1";
export default {
experimental: {
adapter: true
},
engine: "js",
schema: path.join("prisma", "schema.prisma"),
async adapter() {
return new PrismaD1({
CLOUDFLARE_D1_TOKEN: process.env.CLOUDFLARE_D1_TOKEN,
CLOUDFLARE_ACCOUNT_ID: process.env.CLOUDFLARE_ACCOUNT_ID,
CLOUDFLARE_DATABASE_ID: process.env.CLOUDFLARE_DATABASE_ID,
});
},
} satisfies PrismaConfig;
从 Prisma ORM v6.11.0 开始,D1 适配器已从 PrismaD1HTTP 重命名为 PrismaD1。
¥As of Prisma ORM v6.11.0, the D1 adapter has been renamed from PrismaD1HTTP to PrismaD1.
engine(已移除)
¥engine (Removed)
在 Prisma ORM v7 中,engine 属性已被移除。
¥The engine property has been removed in Prisma ORM v7.
For Prisma ORM v6.19 and earlier
配置项目应使用的模式引擎。
¥Configure the schema engine your project should use.
| 属性 | 类型 | 必需的 | 默认 |
|---|---|---|---|
engine | classic 或 js | 不 | classic |
默认情况下,它设置为使用经典引擎,这要求你在 prisma.config.ts 中设置 datasource。
¥By default it is set to use the classic engine, which requires that datasource be set in your prisma.config.ts.
import 'dotenv/config'
import path from "node:path";
import { defineConfig, env } from "prisma/config";
export default defineConfig({
engine: "classic",
datasource: {
url: env('DATABASE_URL'),
},
schema: path.join("prisma", "schema.prisma"),
});
studio(已移除)
¥studio (Removed)
在 Prisma ORM v7 中,studio 属性已被移除。要运行 Prisma Studio,请使用:
¥The studio property has been removed in Prisma ORM v7. To run Prisma Studio, use:
npx prisma studio --config ./prisma.config.ts
Prisma Studio 现在会自动使用 datasource 属性中的连接配置。有关更多详细信息,请参阅 Prisma Studio 文档。
¥Prisma Studio now uses the connection configuration from the datasource property automatically. See the Prisma Studio documentation for more details.
For Prisma ORM v6.19 and earlier
配置 Prisma Studio 如何连接到你的数据库。有关详细信息,请参阅下面的子选项。
¥Configures how Prisma Studio connects to your database. See sub-options below for details.
| 属性 | 类型 | 必需的 | 默认 |
|---|---|---|---|
studio | object | 不 | none |
studio.adapter(已移除)
¥studio.adapter (Removed)
返回 Prisma 驱动程序适配器实例的函数。该函数接收一个包含环境变量的 env 参数,并返回一个解析为有效 Prisma 驱动程序适配器的 Promise 参数。
¥A function that returns a Prisma driver adapter instance. The function receives an env parameter containing environment variables and should return a Promise that resolves to a valid Prisma driver adapter.
| 属性 | 类型 | 必需的 | 默认 |
|---|---|---|---|
studio.adapter | (env: Env) => Promise<SqlMigrationAwareDriverAdapterFactory> | 不 | none |
使用 Prisma ORM LibSQL 驱动程序适配器的示例:
¥Example using the Prisma ORM LibSQL driver adapter:
import type { PrismaConfig } from "prisma";
export default {
experimental: {
studio: true
},
engine: "js",
studio: {
adapter: async (env: Env) => {
const { PrismaLibSQL } = await import("@prisma/adapter-libsql");
const { createClient } = await import("@libsql/client");
const libsql = createClient({
url: env.DOTENV_PRISMA_STUDIO_LIBSQL_DATABASE_URL,
});
return new PrismaLibSQL(libsql);
},
},
} satisfies PrismaConfig;
常见模式
¥Common patterns
设置你的项目
¥Setting up your project
要开始使用 Prisma Config,请在项目根目录中创建一个 prisma.config.ts 文件。你可以使用以下任一方法:
¥To get started with Prisma Config, create a prisma.config.ts file in your project root. You can use either of these approaches:
使用 defineConfig:
¥Using defineConfig:
import 'dotenv/config'
import { defineConfig, env } from "prisma/config";
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: env('DATABASE_URL'),
},
});
使用 TypeScript 类型:
¥Using TypeScript types:
import 'dotenv/config'
import type { PrismaConfig } from "prisma";
import { env } from "prisma/config";
export default {
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: env('DATABASE_URL'),
},
} satisfies PrismaConfig;
使用环境变量
¥Using environment variables
在 Prisma ORM v7 中,运行 prisma init 时,生成的 prisma.config.ts 文件默认包含 import 'dotenv/config'。你必须安装 dotenv 包才能使用环境变量。
¥In Prisma ORM v7, when you run prisma init, the generated prisma.config.ts file includes import 'dotenv/config' by default. You must install the dotenv package to use environment variables.
使用 prisma.config.ts 时,需要显式加载 .env 文件中的环境变量。根据你的运行时和 Node 版本,有几种方法:
¥When using prisma.config.ts, environment variables from .env files need to be loaded explicitly. There are several approaches depending on your runtime and Node version:
使用 dotenv(推荐用于 Prisma ORM v7)
¥Using dotenv (Recommended for Prisma ORM v7)
-
安装
dotenv包:¥Install the
dotenvpackage:
npm install dotenv
-
在
prisma.config.ts文件的顶部导入dotenv/config:¥Import
dotenv/configat the top of yourprisma.config.tsfile:
import 'dotenv/config'
import { defineConfig, env } from "prisma/config";
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
seed: 'tsx prisma/seed.ts',
},
datasource: {
url: env('DATABASE_URL'),
},
});
使用 Node.js v20+ 或带有 --env-file 标志的 tsx
¥Using Node.js v20+ or tsx with --env-file flag
如果使用 Node.js v20+ 或 tsx,你可以传递 --env-file 标志以自动加载环境变量:
¥If using Node.js v20+ or tsx, you can pass a --env-file flag to automatically load environment variables:
tsx --env-file=.env src/index.ts
tsx watch --env-file=.env --env-file=.local.env src/index.ts
tsx --env-file=.env ./prisma/seed.ts
使用 Bun
¥Using Bun
对于 Bun,.env 文件会自动加载,无需额外配置。
¥For Bun, .env files are automatically loaded without additional configuration.
类型安全的环境变量
¥Type-safe environment variables
使用 env() 辅助函数提供对环境变量的类型安全访问:
¥Use the env() helper function to provide type-safe access to environment variables:
import 'dotenv/config'
import { defineConfig, env } from "prisma/config";
type Env = {
DATABASE_URL: string
}
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: env<Env>('DATABASE_URL'),
},
});
处理可选环境变量
¥Handling optional environment variables
如果未定义指定的环境变量,prisma/config 中的 env() 辅助函数会抛出错误。理解这一点很重要,因为:
¥The env() helper function from prisma/config throws an error if the specified environment variable is not defined. This is important to understand because:
-
每个 Prisma CLI 命令都会加载
prisma.config.ts文件。¥Every Prisma CLI command loads the
prisma.config.tsfile -
只有部分命令需要
datasource.url值(例如,prisma db *、prisma migrate *、prisma generate --sql)。¥Only some commands actually need the
datasource.urlvalue (e.g.,prisma db *,prisma migrate *,prisma generate --sql) -
类似
prisma generate的命令不需要数据库 URL,但如果env()在加载配置文件时抛出错误,则该命令仍然会失败。¥Commands like
prisma generatedon't need a database URL, but will still fail ifenv()throws an error when loading the config file
例如,如果你在未设置 DATABASE_URL 的情况下运行 prisma generate,而你的配置使用了 env('DATABASE_URL'),你将看到:
¥For example, if you run prisma generate without DATABASE_URL set, and your config uses env('DATABASE_URL'), you'll see:
Error: PrismaConfigEnvError: Missing required environment variable: DATABASE_URL
解决方案:如果你的环境变量不能保证存在(例如,在 CI/CD 流水线中,你仅运行 prisma generate 进行类型检查),请不要使用 env() 辅助函数。或者,直接访问环境变量:
¥Solution: If your environment variable isn't guaranteed to exist (e.g., in CI/CD pipelines where you only run prisma generate for type-checking), don't use the env() helper. Instead, access the environment variable directly:
import 'dotenv/config'
import { defineConfig } from "prisma/config";
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: process.env.DATABASE_URL!, // Or use: process.env.DATABASE_URL ?? '' to provide a fallback value
},
});
当你想要强制环境变量存在时,请使用 env() 辅助函数。如果变量可能因运行的命令而可选,则可直接使用 process.env。
¥Use the env() helper when you want to enforce that an environment variable exists. Use process.env directly when the variable may be optional depending on the command being run.
使用多文件模式
¥Using multi-file schemas
如果你要将 Prisma 模式拆分为多个文件,则需要通过 schema 属性指定 Prisma 模式文件夹的路径:
¥If you want to split your Prisma schema into multiple files, you need to specify the path to your Prisma schema folder via the schema property:
import path from "node:path";
import type { PrismaConfig } from "prisma";
export default {
schema: path.join("prisma", "schema"),
} satisfies PrismaConfig;
在这种情况下,你的 migrations 目录必须位于定义 datasource 块的 .prisma 文件旁边。
¥In that case, your migrations directory must be located next to the .prisma file that defines the datasource block.
例如,假设 schema.prisma 定义了 datasource,则迁移文件夹的放置方式如下:
¥For example, assuming schema.prisma defines the datasource, here's how how need to place the migrations folder:
# `migrations` and `schema.prisma` are on the same level
.
├── migrations
├── models
│ ├── posts.prisma
│ └── users.prisma
└── schema.prisma
路径解析
¥Path resolution
Prisma CLI 命令(例如 prisma validate 或 prisma migrate)使用 prisma.config.ts(或 .config/prisma.ts)来定位 Prisma 模式和其他资源。
¥Prisma CLI commands such as prisma validate or prisma migrate use prisma.config.ts (or .config/prisma.ts) to locate your Prisma schema and other resources.
关键规则:
¥Key rules:
-
配置文件中定义的路径(例如
schema、migrations)始终相对于配置文件的位置解析,而不是你运行 CLI 命令的位置。¥Paths defined in the config file (e.g.,
schema,migrations) are always resolved relative to the location of the config file, not where you run the CLI command from. -
CLI 首先必须找到配置文件本身,这取决于 Prisma 的安装方式和所使用的包管理器。
¥The CLI must first find the config file itself, which depends on how Prisma is installed and the package manager used.
使用 pnpm prisma 的行为
¥Behavior with pnpm prisma
当 Prisma 在本地安装并通过 pnpm prisma 运行时,无论你是从项目根目录还是子目录运行命令,都会自动检测配置文件。
¥When Prisma is installed locally and run via pnpm prisma, the config file is detected automatically whether you run the command from the project root or a subdirectory.
示例项目树:
¥Example project tree:
.
├── node_modules
├── package.json
├── prisma-custom
│ └── schema.prisma
├── prisma.config.ts
└── src
从项目根目录运行示例:
¥Example run from the project root:
pnpm prisma validate
# → Loaded Prisma config from ./prisma.config.ts
# → Prisma schema loaded from prisma-custom/schema.prisma
从子目录运行示例:
¥Example run from a subdirectory:
cd src
pnpm prisma validate
# → Still finds prisma.config.ts and resolves schema correctly
使用 npm exec prisma 或 bun prisma 的行为
¥Behavior with npm exec prisma or bun prisma
当通过 npm exec prisma 或 bun prisma 运行时,CLI 仅当命令从项目根目录(其中 package.json 声明了 Prisma)运行时才会检测配置文件。
¥When running via npm exec prisma or bun prisma, the CLI only detects the config file if the command is run from the project root (where package.json declares Prisma).
从项目根目录运行示例:
¥Example run from the project root:
npm exec prisma validate
# → Works as expected
从子目录运行(失败):
¥Run from a subdirectory (fails):
cd src
npm exec prisma validate
# → Error: Could not find Prisma Schema...
要解决此问题,你可以使用 --config 标志:
¥To fix this, you can use the --config flag:
npm exec prisma -- --config ../prisma.config.ts validate
全球 Prisma 安装
¥Global Prisma installations
如果 Prisma 是全局安装的(npm i -g prisma),默认情况下它可能找不到你的 prisma.config.ts 或 prisma/config 模块。避免问题:
¥If Prisma is installed globally (npm i -g prisma), it may not find your prisma.config.ts or prisma/config module by default.
To avoid issues:
-
建议在项目中本地安装 Prisma。
¥Prefer local Prisma installations in your project.
-
或者在本地使用
prisma/config,并将--config传递到你的配置文件。¥Or use
prisma/configlocally and pass--configto point to your config file.
Monorepos
-
如果 Prisma 安装在工作区根目录中,
pnpm prisma将从子目录中检测配置文件。¥If Prisma is installed in the workspace root,
pnpm prismawill detect the config file from subdirectories. -
如果 Prisma 安装在子包中(例如
./packages/db),请从该包目录或更深层次的目录中运行命令。¥If Prisma is installed in a subpackage (e.g.,
./packages/db), run commands from that package directory or deeper.
自定义配置位置
¥Custom config location
你可以在运行 Prisma CLI 命令时为配置文件指定自定义位置:
¥You can specify a custom location for your config file when running Prisma CLI commands:
prisma validate --config ./path/to/myconfig.ts
加载环境变量
¥Loading environment variables
在 Prisma ORM v7 中,prisma init 会自动生成一个 prisma.config.ts 文件。要使用 dotenv 加载环境变量,请执行以下操作:
¥In Prisma ORM v7, prisma init generates a prisma.config.ts file automatically. To load environment variables with dotenv, do the following:
-
安装
dotenv包。¥Install the
dotenvpackage. -
在
prisma.config.ts文件的顶部添加import 'dotenv/config'。¥Add
import 'dotenv/config'at the top of yourprisma.config.tsfile.
这是 Prisma 从你的 .env 文件中读取值所必需的。
¥This is required for Prisma to read values from your .env file.
要在 Prisma 应用中加载环境变量,你可以将 prisma.config.ts 文件与 prisma/config 中的 env 辅助程序一起使用。这种方法提供了更好的类型安全性和配置管理。
¥To load environment variables in your Prisma application, you can use the prisma.config.ts file along with the env helper from prisma/config. This approach provides better type safety and configuration management.
-
安装
dotenv包:¥Install the
dotenvpackage:npm install dotenv -
在项目根目录中创建
.env文件(如果不存在),并添加数据库连接字符串:¥Create a
.envfile in your project root (if it doesn't exist) and add your database connection string:DATABASE_URL="your_database_connection_string_here" -
确保你的
prisma.config.ts文件顶部导入了dotenv/config:¥Ensure your
prisma.config.tsfile importsdotenv/configat the top:prisma.config.tsimport 'dotenv/config'
import { defineConfig, env } from "prisma/config";
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
seed: 'tsx prisma/seed.ts',
},
datasource: {
url: env("DATABASE_URL"),
},
});