# @electric-sql/prisma-generator 中文文档

规范地址：https://npmcn.com/package/%40electric-sql/prisma-generator/

版本：1\.1\.5
npm 元数据更新时间：2026-01-30T21:50:04.886Z
中文译文更新时间：2026-11-13T23:35:25.781Z
软件包许可：未声明

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40electric-sql/prisma-generator
原文对照：https://npmcn.com/package/%40electric-sql/prisma-generator/?lang=original
项目主页：https://github.com/chrishoermann/zod-prisma-types#readme
源码仓库：https://github.com/chrishoermann/zod-prisma-types

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：530 kB，375 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：4 个
- 首次发布：2023-07-17T16:06:40.134Z
- 最新版本发布：2024-05-07T08:16:19.068Z
- 近 30 天下载量：2878（2026-10-14 至 2026-11-12，npm 官方下载统计）
- 已发布版本数：10（近 12 个月 0 个）

## 中文简介

一个 Prisma 生成器,使用 Zod-prisma 类型生成的 schemas 创建 DB 描述对象.

## 安装

```sh
npm install @electric-sql/prisma-generator
```

也可以使用：`pnpm add @electric-sql/prisma-generator`、`yarn add @electric-sql/prisma-generator`、`bun add @electric-sql/prisma-generator`

## README

# zod-prisma 类型

> 此目录来自 [https://github.com/chrishoermann/zod-prisma-types (中文(简体) )](https://github.com/chrishoermann/zod-prisma-types)

`zod-prisma-types` 是一个用于 [棱镜](https://www.prisma.io/) 生成 [佐德语](https://github.com/colinhacks/zod) 你的棱镜模型的图案 这包括模型,enums,输入Types,agTypes,过滤器等的图案. 它还提供了直接将高级的zod验证器写入棱镜schema注释的选项.

因为我在业余时间维持发电机 考虑请我喝杯咖啡 或者赞助我 如果你喜欢这个项目的话 谢谢!

## V2.x.x中突破变化

注意一些生成器选项被移除,添加了几个新内容,自定义导入行为发生改变,再不需要ts-morph来生成v2.0.0中的文件.

## 已知问题

> 自兹 `zod version 3.21.2` 一些计程器会丢出打字错误 。 请使用 `zod version 3.21.1` 直到这个问题得到解决.

## 目录

-   [关于这个项目](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-about-this-project)
-   [安装](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-installation)
-   [使用量](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-usage)
    -   [`output`](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-output)
    -   [`useMultipleFiles`](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-usemultiplefiles)
    -   [`createInputTypes`](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-createinputtypes)
    -   [`createModelTypes`](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-createmodeltypes)
    -   [`addInputTypeValidation`](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-addinputtypevalidation)
    -   [`addIncludeType`](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-addincludetype)
    -   [`addSelectType`](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-addselecttype)
    -   [`validateWhereUniqueInput`](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-validatewhereuniqueinput)
    -   [`createOptionalDefaultValuesTypes`](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-createoptionaldefaultvaluestypes)
    -   [`createRelationValuesTypes`](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-createrelationvaluestypes)
    -   [`createPartialTypes`](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-createpartialtypes)
    -   [`useDefaultValidators`](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-usedefaultvalidators)
    -   [`coerceDate`](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-coercedate)
    -   [`writeNullishInModelTypes`](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-writenullishinmodeltypes)
    -   [`prismaClientPath`](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-prismaclientpath)
-   [跳过计划生成](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-skip-schema-generation)
-   [自定义 Enums](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-custom-enums)
-   [Json 无效值](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-json-null-values)
-   [小数](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-decimal)
-   [字段验证器](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-field-validators)
    -   [自定义导入](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-custom-imports)
    -   [自定义类型错误消息](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-custom-type-error-messages)
    -   [字符串验证符](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-string-validators)
    -   [数字验证符](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-number-validators)
    -   [BigInt 验证器](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-bigint-validators)
    -   [日期验证符](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-date-validators)
    -   [自定义验证符](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-custom-validators)
    -   [矩阵验证符](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-array-validators)
    -   [缩写字段](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-omit-fields)
    -   [校验错误](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-validation-errors)
-   [命名 Zod 计划](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-naming-of-zod-schemas)
-   [添加注释](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-adding-comments)
-   [从 `zod-prisma`](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-migration-from-zod-prisma)
    -   [发电机选项](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-generator-options)
    -   [扩展 Zod 字段](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-extending-zod-fields)
    -   [导入助手](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-importing-helpers)

## 关于这个项目

对于我的一个项目,我需要一台发电机 提供增加的可能性 `zod valdiators` 直接输入 `prisma schema's` [富人评论](https://www.prisma.io/docs/concepts/components/prisma-schema#comments) 生成 `zod` 用于所有棱镜模型,enums,输入Types,agTypes,滤镜等的图案. 我也希望能在前端导入这些图案,例如用于形式验证,并使生成器像多管所一样灵活,从而涵盖大量使用案例. 因为那里没有能满足我要求的发电机 或者它们不再活动维护 我决定写作 `zod-prisma-type`。 。 。 .

## 安装

> 传统发展

## 使用量

> 支持棱镜 4.x

将以下代码添加到您的 `prisma.schema` 要创建单个文件的文件 `index.ts` 文档中 `./generated/zod` 包含全部 zod 棱镜图案的输出文件夹 .

```prisma
generator zod {
  provider       = "zod-prisma-types"
}
```

然后将计划导入到您的文件中:

```ts
import { mySchema } from '/prisma/generated/zod' // All schemas are here by default, use the 'output' option to change it
```

> 如果遇到以下错误 `/bin/sh: zod-prisma-types: command not found` 请尝试使用 `npx` 命令与 `zod-prisma-types` 命令.

```prisma
generator zod {
  provider       = "npx zod-prisma-types"
}
```

如果您想要自定义生成器的行为, 您可以使用以下选项:

```prisma
generator zod {
  provider                         = "ts-node-dev ../generator/src/bin.ts"
  output                           = "./generated/zod" // default is ./generated/zod
  useMultipleFiles                 = true // default is false
  createInputTypes                 = false // default is true
  createModelTypes                 = false // default is true
  addInputTypeValidation           = false // default is true
  addIncludeType                   = false // default is true
  addSelectType                    = false // default is true
  validateWhereUniqueInput         = true // default is false
  createOptionalDefaultValuesTypes = true // default is false
  createRelationValuesTypes        = true // default is false
  createPartialTypes               = true // default is false
  useDefaultValidators             = false // default is true
  coerceDate                       = false // default is true
  writeNullishInModelTypes         = true // default is false
  prismaClientPath                 = "./path/to/prisma/client" // default is client output path
}
```

### `useMultipleFiles`

> 默认 : `false`

如果您想要创建多个文件而不是一个文件 `index.ts` 文件可以设置此选项 `true`。这将为每个模型、enum、involutionType、argType、过滤器等创建文件。 这些文件将在指定的输出文件夹中的子文件夹中创建,并在输出文件夹的根部会添加一个桶文件.

```prisma
generator zod {
  // ...rest of config
  useMultipleFiles = false
}
```

### `output`

> 默认 : `./generated/zod`

提供替代输出路径 .

### `createInputTypes`

> 默认 : `true`

如果您只想为您的模型和enum创建zod schemas, 您可以禁用相应的输入类型的创建 。 如果您想要使用您的模型的 zod 方案来验证输入类型, 这可能是有益的 `react-hook-form` 或一些类似的使用案例.

```prisma
generator zod {
  // ...rest of config
  createInputTypes = false
}
```

### `createModelTypes`

> 默认 : `true`

如果您想要为输入类型创建 Zod 计划, 您可以禁用相应的模型计划 。 如果您想要在 Trpc 查询或类似的使用上使用 zod 输入策略来自动补全, 这可能有用 .

```prisma
generator zod {
  // ...rest of config
  createModelTypes = false
}
```

### `addInputTypeValidation`

> 默认 : `true`

如果您想要使用您的自定义 zod 验证符, 您只通过丰富的注释在您生成的模型图中添加, 而不是您创建的输入类型图中添加( ) `UserCreateInput`, (中文(简体) ), `UserUpdateManyInput`等),可以禁用此特性.

```prisma
generator zod {
  // ...rest of config
  addInputTypeValidation = false
}
```

### `addIncludeType`

> 默认 : `true`

默认情况下,将包含类型添加到 `[Model]ArgTypeSchema`。如果您不想添加 Zod 计划 `include` 类型 `false`。 。 。 .

```prisma
generator zod {
  // ...rest of config
  addIncludeType = false
}
```

### `addSelectType`

> 默认 : `true`

默认情况下,选定类型将添加到 `[Model]ArgTypeSchema`。如果您不想添加 Zod 计划 `select` 类型 `false`。 。 。 .

```prisma
generator zod {
  // ...rest of config
  addSelectType = false
}
```

### `validateWhereUniqueInput`

> 默认 : `false`

默认生成器不会验证 `whereUnique` 多文件模式的输入类型,因为经常会生成一批未使用的导入. 如果你想验证 `whereUnique` 您可以设置此选项的输入类型 `true`。 。 。 .

> 请注意,如果使用Eslint系统,可能导致Eslint错误 `no-unused-vars` 规则需要手动解决.

```prisma
generator zod {
  // ...rest of config
  validateWhereUniqueInput = true
}
```

### `createOptionalDefaultValuesTypes`

> 默认 : `false`

如果您想要将默认值的字段标为 `.optional()` 您可以通过以下配置选项:

```prisma
generator zod {
  // ...rest of config
  createOptionalDefaultValuesTypes = true
}

model ModelWithDefaultValues {
  id          Int      @id @default(autoincrement())
  string      String   @default("default")
  otherString String
  int         Int      @default(1)
  otherInt    Int
  float       Float    @default(1.1)
  otherFloat  Float
  boolean     Boolean  @default(true)
  otherBool   Boolean
  date        DateTime @default(now())
  otherDate   DateTime
}
```

上述模型将产生以下模型计划:

```ts
export const ModelWithDefaultValuesSchema = z.object({
  id: z.number(),
  string: z.string(),
  otherString: z.string(),
  int: z.number(),
  otherInt: z.number(),
  float: z.number(),
  otherFloat: z.number(),
  boolean: z.boolean(),
  otherBool: z.boolean(),
  date: z.date(),
  otherDate: z.date(),
})

export const ModelWithDefaultValuesOptionalDefaultsSchema =
  ModelWithDefaultValuesSchema.merge(
    z.object({
      id: z.number().optional(),
      string: z.string().optional(),
      int: z.number().optional(),
      float: z.number().optional(),
      boolean: z.boolean().optional(),
      date: z.date().optional(),
    })
  )
```

### `createRelationValuesTypes`

> 默认 : `false`

如果您需要包含所有关系字段的单独的模型类型,您可以通过以下选项。 由于需要有递归型的注释类型,该模型自此具有一些局限性 `z.ZodType<myType>` 不允许像 `.merge()`, (中文(简体) ), `.omit()`等 (中文(简体) ).

```prisma
generator zod {
  // ...rest of config
  createRelationValuesTypes = true
}

model User {
  id         String      @id @default(cuid())
  email      String      @unique
  name       String?
  posts      Post[]
  profile    Profile?
  role       Role[]      @default([USER, ADMIN])
  enum       AnotherEnum @default(ONE)
  scalarList String[]

  lat Float
  lng Float

  location Location? @relation(fields: [lat, lng], references: [lat, lng])
}
```

上述模型将产生以下模型计划:

```ts
export const UserSchema = z.object({
  role: RoleSchema.array(),
  enum: AnotherEnumSchema,
  id: z.string().cuid(),
  email: z.string(),
  name: z.string().optional(),
  scalarList: z.string().array(),
  lat: z.number(),
  lng: z.number(),
})

export type UserRelations = {
  posts: PostWithRelations[]
  profile?: ProfileWithRelations | null
  location?: LocationWithRelations | null
}
export type UserWithRelations = z.infer<typeof UserSchema> & UserRelations

export const UserWithRelationsSchema: z.ZodType<UserWithRelations> =
  UserSchema.merge(
    z.object({
      posts: z.lazy(() => PostWithRelationsSchema).array(),
      profile: z.lazy(() => ProfileWithRelationsSchema).nullish(),
      location: z.lazy(() => LocationWithRelationsSchema).nullish(),
    })
  )
```

如果将选项与 `createOptionalDefaultValuesTypes` 此外,还生成下列模型计划:

```ts
export type UserOptionalDefaultsWithRelations = z.infer<
  typeof UserOptionalDefaultsSchema
> &
  UserRelations

export const UserOptionalDefaultsWithRelationsSchema: z.ZodType<UserOptionalDefaultsWithRelations> =
  UserOptionalDefaultsSchema.merge(
    z.object({
      posts: z.lazy(() => PostWithRelationsSchema).array(),
      profile: z.lazy(() => ProfileWithRelationsSchema).nullable(),
      location: z.lazy(() => LocationWithRelationsSchema).nullable(),
      target: z.lazy(() => LocationWithRelationsSchema).nullable(),
    })
  )
```

### `createPartialTypes`

> 默认 : `false`

如果您需要单独的模型类型,其中包含所有可选字段,您可以通过以下选项.

```prisma
generator zod {
  // ...rest of config
  createPartialTypes = true
}

model User {
  id         String      @id @default(cuid())
  email      String      @unique
  name       String?
  posts      Post[]
  profile    Profile?
  role       Role[]      @default([USER, ADMIN])
  enum       AnotherEnum @default(ONE)
  scalarList String[]

  lat Float
  lng Float

  location Location? @relation(fields: [lat, lng], references: [lat, lng])
}
```

上述模型将产生以下模型计划:

```ts
export const UserPartialSchema = z
  .object({
    role: RoleSchema.array(),
    enum: AnotherEnumSchema,
    id: z.string().cuid(),
    email: z.string().email({ message: 'Invalid email address' }),
    name: z.string().min(1).max(100).nullable(),
    scalarList: z.string().array(),
    lat: z.number(),
    lng: z.number(),
  })
  .partial()
```

当结合使用此选项时 `createRelationValuesTypes` 以下模型计划也生成。 这种模型具有一些局限性 `z.ZodType<myType>` 不允许像 `.merge()`, (中文(简体) ), `.omit()`等 (中文(简体) ).

```ts
export type UserPartialRelations = {
  posts?: PostPartialWithRelations[]
  profile?: ProfilePartialWithRelations | null
  location?: LocationPartialWithRelations | null
}

export type UserPartialWithRelations = z.infer<typeof UserPartialSchema> &
  UserPartialRelations

export const UserPartialWithRelationsSchema: z.ZodType<UserPartialWithRelations> =
  UserPartialSchema.merge(
    z.object({
      posts: z.lazy(() => PostPartialWithRelationsSchema).array(),
      profile: z.lazy(() => ProfilePartialWithRelationsSchema).nullable(),
      location: z.lazy(() => LocationPartialWithRelationsSchema).nullable(),
    })
  ).partial()
```

导出类型 UserPartial = z.infer;

### `useDefaultValidators`

> 默认 : `true`

在某些情况下,生成器会添加默认验证符:

```prisma
model WithDefaultValidators {
  id      String @id @default(cuid())
  idTwo   String @default(uuid())
  integer Int
}
```

```ts
export const WithDefaultValidatorsSchema = z.object({
  id: z.string().cuid(),
  idTwo: z.string().uuid(),
  integer: z.number().int(),
})
```

这些默认值在使用自定义验证符时被覆盖(参见: [实地验证器](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-field-validators)(中文(简体) ) 或选择退出在特定字段使用默认验证符时:

```prisma
model WithDefaultValidators {
  id      String @id @default(cuid()) /// @zod.string.noDefault()
  idTwo   String @default(uuid()) /// @zod.string.noDefault()
  integer Int    /// @zod.number.noDefault()
}
```

```ts
export const WithDefaultValidatorsSchema = z.object({
  id: z.string(),
  idTwo: z.string(),
  integer: z.number(),
})
```

您可以完全选择退出此特性, 将错误传递到配置选项 .

```prisma
generator zod {
  // ...rest of config
  useDefaultValidators = false
}
```

> 计划在未来的发布中(通过检查图中的@db.filds)进行更多的默认验证. 如果您对默认验证器有一些想法, 可以随意打开一个问题 .

### `coerceDate`

> 默认: 真

默认 `DateTime` 价值观受到胁迫 `Date` 对象,只要你通过在一个 `valid ISO string` 或一个 `instance of Date`。可以改变此行为以生成一个简单的 `z.date()` 将以下选项传递给生成器配置:

```prisma
generator zod {
  // ...rest of config
  coerceDate = false
}
```

### `writeNullishInModelTypes`

> 默认: 假

默认情况下,生成器只是写 `.nullable()` 在模型Types中,当Prisma类型的字段无效时。 如果你想要这些字段接受 `null | undefined`页:1 `.nullish()` 在设计图中,可以将以下选项传递给生成器配置 :

```prisma
generator zod {
  // ...rest of config
  writeNullishInModelTypes = true
}
```

### `prismaClientPath`

> 默认 : `infereed from prisma schema path`

默认情况下, prisma 客户端路径会从 `output` 路径 `prisma.schema` 文件编号 `generator client`。如果还需要使用自定义路径,您可以通过此选项将其传递给生成器配置。 自定义路径优先于受难棱镜客户端输出路径.

```prisma
generator zod {
  // ...rest of config
  prismaClientPath = "./path/to/prisma/client"
}
```

## 跳过计划生成

您可以跳过基于您当前工作环境的生成计划 。 举例来说,只有在你加入时才能生成计划 `development` 但当你运行世代在 `production` (因为 `production` 计划早就被创建了 并且通过您的 git repo 推向服务器了.

既然Prisma只让我们定义 `strings` 在生成器配置中我们不能使用 `env(MY_ENV_VARIABLE)` 使用方法,例如: `url` 下级 `datasource db` 已装入 :

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

要仍然能够将环境变量加载到生成器中,只需创建一个 `zodGenConfig.js` 在您的根目录中 `node_modules` 文件夹位于)并添加以下代码:

```ts
module.exports = {
  skipGenerator: process.env['SKIP_ZOD_PRISMA'],
}
```

然后添加

```js
SKIP_ZOD_PRISMA = 'true'
```

或者说

```js
SKIP_ZOD_PRISMA = 'false'
```

给您的 `.env` 文档。 这将加载 `SKIP_ZOD_PRISMA` 环境变量 `skipGenerator` 然后由发电机消耗的道具.

> 您可以选择指定您想要的环境变量 `zodGenConfig.js`。 。 。 .

## 自定义 Enums

对于自定义的enums,生成一个单独的类型,代表作为结合的enum值. 由于在打字联盟中比注字联盟更有用,这可以有所帮助.

```prisma
enum MyEnum {
  A
  B
  C
}
```

```ts
export const MyEnumSchema = z.nativeEnum(PrismaClient.MyEnum)

export type MyEnumType = `${z.infer<typeof MyEnumSchema>}` // union of "A" | "B" | "C"
```

## Json 无效值

当使用 json 虚值 棱镜时, 它有独特的处理数据库的方法 `NULL` 和JSON项目 `null` 如所述 [文档中](https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#using-null-values)。 。 。 .

为了坚持这个概念,你可以通过 `"DbNull"` 或者说 `"JsonNull"` 作为无效的 Json 字段的字符串。 当计划被验证后,这些字符串被转换为 `Prisma.DbNull` 或者说 `Prisma.JsonNull` 满足 `prisma.[myModel].create() | .update() | ...` 函数.

## 小数

当使用十进制 a `refine` 如果输入坚持棱镜输入结合,则使用方法验证 `string | number | Decimal | DecimalJsLike`。 。 。 .

```prisma
model MyModel {
  id      Int     @id @default(autoincrement())
  decimal Decimal
}
```

上述模式将产生以下计划:

```ts
// DECIMAL HELPERS
//------------------------------------------------------

export const DecimalJSLikeSchema: z.ZodType<Prisma.DecimalJsLike> = z.object({
  d: z.array(z.number()),
  e: z.number(),
  s: z.number(),
  toFixed: z.function().args().returns(z.string()),
})

export const DecimalJSLikeListSchema: z.ZodType<Prisma.DecimalJsLike[]> = z
  .object({
    d: z.array(z.number()),
    e: z.number(),
    s: z.number(),
    toFixed: z.function().args().returns(z.string()),
  })
  .array()

export const DECIMAL_STRING_REGEX = /^[0-9.,e+-bxffo_cp]+$|Infinity|NaN/

export const isValidDecimalInput = (
  v?: null | string | number | Prisma.DecimalJsLike
): v is string | number | Prisma.DecimalJsLike => {
  if (v === undefined || v === null) return false
  return (
    (typeof v === 'object' &&
      'd' in v &&
      'e' in v &&
      's' in v &&
      'toFixed' in v) ||
    (typeof v === 'string' && DECIMAL_STRING_REGEX.test(v)) ||
    typeof v === 'number'
  )
}
// SCHEMA
//------------------------------------------------------

export const MyModelSchema = z.object({
  id: z.number(),
  decimal: z
    .union([z.number(), z.string(), DecimalJSLikeSchema])
    .refine((v) => isValidDecimalInput(v), {
      message:
        "Field 'decimal' must be a Decimal. Location: ['Models', 'DecimalModel']",
    }),
})
```

## 字段验证器

可以在 注释中添加 zod 验证符 `prisma.schema` 使用下列语法的文件 [富人评论](https://www.prisma.io/docs/concepts/components/prisma-schema#comments) `///` 改为 `//`) (中文(简体) ).

```prisma
myField [prisma-scalar-type] /// @zod.[zod-type + optional[(zod-error-messages)]].[zod validators for scalar-type]
```

这看起来有点隐秘 所以这里有一个例子:

```prisma
generator zod {
  provider       = "zod-prisma-types"
  output         = "./zod"
}

/// @zod.import(["import { myFunction } from 'mypackage';"])
model MyPrismaScalarsType {
  /// @zod.string({ invalid_type_error: "some error with special chars: some + -*#'substring[]*#!§$%&/{}[]", required_error: "some other", description: "some description" }).cuid()
  id         String    @id @default(cuid())
  /// Some comment about string @zod.string.min(3, { message: "min error" }).max(10, { message: "max error" })
  string     String?
  /// @zod.custom.use(z.string().refine((val) => validator.isBIC(val), { message: 'BIC is not valid' }))
  bic        String?
  /// @zod.number.lt(10, { message: "lt error" }).gt(5, { message: "gt error" })
  float      Float
  floatOpt   Float?
  /// @zod.number.int({ message: "error" }).gt(5, { message: "gt error" })
  int        Int
  intOpt     Int?
  decimal    Decimal
  decimalOpt Decimal?
  date       DateTime  @default(now())
  dateOpt    DateTime? /// @zod.date({ invalid_type_error: "wrong date type" })  bigInt     BigInt /// @zod.bigint({ invalid_type_error: "error" })
  bigIntOpt  BigInt?
  /// @zod.custom.use(z.lazy(() => InputJsonValue).refine((val) => myFunction(val), { message: 'Is not valid' }))
  json       Json
  jsonOpt    Json?
  bytes      Bytes /// @zod.custom.use(z.instanceof(Buffer).refine((val) => val ? true : false, { message: 'Value is not valid' }))
  bytesOpt   Bytes?
  /// @zod.custom.use(z.string().refine((val) => myFunction(val), { message: 'Is not valid' }))
  custom     String?
  exclude    String? /// @zod.custom.omit(["model", "input"])

  updatedAt DateTime @updatedAt
}
```

此示例为模型生成以下 Zod 计划 `prisma/zod/index.ts`数字 :

```ts
import { z } from 'zod'
import * as PrismaClient from '@prisma/client'
import validator from 'validator'
import { myFunction } from 'mypackage'

export const MyPrismaScalarsTypeSchema = z.object({
  id: z
    .string({
      invalid_type_error:
        "some error with special chars: some + -*#'substring[]*#!§$%&/{}[]",
      required_error: 'some other',
      description: 'some description',
    })
    .cuid(),
  /**
   * Some comment about string
   */
  string: z
    .string()
    .min(3, { message: 'min error' })
    .max(10, { message: 'max error' })
    .nullish(),
  bic: z
    .string()
    .refine((val) => validator.isBIC(val), { message: 'BIC is not valid' })
    .nullish(),
  float: z
    .number()
    .lt(10, { message: 'lt error' })
    .gt(5, { message: 'gt error' }),
  floatOpt: z.number().nullish(),
  int: z.number().int({ message: 'error' }).gt(5, { message: 'gt error' }),
  intOpt: z.number().int().nullish(),
  decimal: z
    .union([
      z.number(),
      z.string(),
      z.instanceof(PrismaClient.Prisma.Decimal),
      DecimalJSLikeSchema,
    ])
    .refine((v) => isValidDecimalInput(v), {
      message: 'Field "decimal" must be a Decimal',
      path: ['Models', 'MyPrismaScalarsType'],
    }),
  decimalOpt: z
    .union([
      z.number(),
      z.string(),
      z.instanceof(PrismaClient.Prisma.Decimal),
      DecimalJSLikeSchema,
    ])
    .refine((v) => isValidDecimalInput(v), {
      message: 'Field "decimalOpt" must be a Decimal',
      path: ['Models', 'MyPrismaScalarsType'],
    })
    .nullish(),
  date: z.coerce.date(),
  dateOpt: z.coerce.date({ invalid_type_error: 'wrong date type' }).nullish(),
  bigIntOpt: z.bigint().nullish(),
  json: z
    .lazy(() => InputJsonValue)
    .refine((val) => myFunction(val), { message: 'Is not valid' }),
  jsonOpt: NullableJsonValue.optional(),
  bytes: z
    .instanceof(Buffer)
    .refine((val) => (val ? true : false), { message: 'Value is not valid' }),
  bytesOpt: z.instanceof(Buffer).nullish(),
  custom: z
    .string()
    .refine((val) => myFunction(val), { message: 'Is not valid' })
    .nullish(),
  // omitted: exclude: z.string().nullish(),
  updatedAt: z.date(),
})

export type MyPrismaScalarsType = z.infer<typeof MyPrismaScalarsTypeSchema>

export const MyPrismaScalarsTypeOptionalDefaultsSchema =
  MyPrismaScalarsTypeSchema.merge(
    z.object({
      id: z
        .string({
          invalid_type_error:
            "some error with special chars: some + -*#'substring[]*#!§$%&/{}[]",
          required_error: 'some other',
          description: 'some description',
        })
        .cuid()
        .optional(),
      date: z.date().optional(),
      updatedAt: z.date().optional(),
    })
  )
```

> 此外,所有用于棱镜输入的zod schemas-, enum-, filter-, orderBy-, selected-, 包括和其他必要类型, 都可以用于例如. `trpc` 投入.

## 自定义导入

要将自定义导入添加到您的验证器中, 您可以通过 `@zod.import([...myCustom imports as strings])` 在棱镜中对模型定义的丰富评论.

例如:

```prisma
/// @zod.import(["import { myFunction } from 'mypackage'"])
model MyModel {
  myField String /// @zod.string().refine((val) => myFunction(val), { message: 'Is not valid' })
}
```

这将产生如下产出:

```ts
import { myFunction } from 'mypackage'

export const MyModelSchema = z.object({
  myField: z
    .string()
    .refine((val) => myFunction(val), { message: 'Is not valid' }),
})
```

> 请注意,如果使用此选项,您必须在相对进口中添加一个级别 `useMultipleFiles` 选项.

## 自定义类型错误消息

要将自定义的 zod- 类型错误消息添加到您的验证器中, 您可以通过 `@zod.[key]({ ...customTypeErrorMessages }).[validator key]`。自定义错误信息必须坚持以下类型:

```ts
type RawCreateParams =
  | {
      invalid_type_error?: string
      required_error?: string
      description?: string
    }
  | undefined
```

例如:

```prisma
model MyModel {
  myField String /// @zod.string({ invalid_type_error: "invalid type error", required_error: "is required", description: "describe the error" })
}
```

这将产生如下产出:

```ts
 string: z.string({
    invalid_type_error: 'invalid type error',
    required_error: 'is required',
    description: 'describe the error',
  }),
```

如果您使用错误的密钥或有打字符, 生成器会丢出错误 :

```prisma
model MyModel {
  myField String  /// @zod.string({ required_error: "error", invalid_type_errrrrror: "error"})
}
```

```bash
[@zod generator error]: Custom error key 'invalid_type_errrrrror' is not valid. Please check for typos! [Error Location]: Model: 'Test', Field: 'myField'.
```

## 字符串验证符

在棱镜中添加自定义验证符 `String` 字段可以使用 `@zod.string` 键。 您可以在此键上使用在 [`zod-docs`](https://github.com/colinhacks/zod#strings)。也可以按照文件中的规定,在每个验证器中添加自定义错误消息.

```prisma
model MyModel {
  myField String /// @zod.string.min(3, { message: "min error" }).max(10, { message: "max error" }).[...chain more validators]
}
```

## 数字验证符

在棱镜中添加自定义验证符 `Int` 或者说 `Float` 字段可以使用 `@zod.number` 键。 在此密钥上, 您可以使用您在 [`zod-docs`](https://github.com/colinhacks/zod#numbers)。也可以按照文件中的规定,在每个验证器中添加自定义错误消息.

```prisma
model MyModel {
  myField Int
/// @zod.number.lt(10, { message: "lt error" }).gt(5, { message: "gt error" }).[...chain more validators]
}
```

## BigInt 验证器

在棱镜中添加自定义验证符 `BigInt` 字段可以使用 `@zod.bigint` 键。 您可以在此键上使用在 [`zod-docs`](https://github.com/colinhacks/zod#bigints)。也可以按照文件中的规定,在每个验证器中添加自定义错误消息.

```prisma
model MyModel {
  myField BigInt /// @zod.bigint.lt(5n, { message: "lt error" }).gt(6n, { message: "gt error" })({ invalid_type_error: "error", ... }).[...chain more validators]
}
```

## 日期验证符

在棱镜中添加自定义验证符 `DateTime` 字段可以使用 `@zod.date` 键。 在此键上,您可以使用您在 [`zod-docs`](https://github.com/colinhacks/zod#dates)。也可以按照文件中的规定,在每个验证器中添加自定义错误消息.

```prisma
model MyModel {
  myField DateTime ///  @zod.date.min(new Date('2020-01-01')).max(new Date('2020-12-31'))
}
```

## 自定义验证符

将自定义验证符添加到任意 [`Prisma Scalar`](https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#model-field-scalar-types) 字段可以使用 `@zod.custom.use()` 键。 这个键只有 `.use(...your custom code here)` 验证器。 此代码覆盖所有其他标准执行, 因此您必须精确指定 `zod type` 如何由生成器写出来。 仅 `.optional()` 财务报告和审定财务报表 `.nullable()` 根据您的棱镜型式定义自动添加。 此字段被插入以提供像 Zod 这样的验证器 `.refine` 或者说 `.transform` 在你的地盘上.

```prisma
model MyModel {
  id     Int     @id @default(autoincrement())
  custom String? /// @zod.custom.use(z.string().refine(val => validator.isBIC(val)).transform(val => val.toUpperCase()))
}
```

上述模型计划将产生以下zod计划:

```ts
export const MyModel = z.object({
  id: z.number(),
  custom: z
    .string()
    .refine((val) => validator.isBIC(val))
    .transform((val) => val.toUpperCase())
    .nullable(),
})
```

## 矩阵验证符

要添加自定义验证符以列出字段, 您可以使用 `z.[key].array(.length(2).min(1).max(2).nonempty())` 验证器。 您可以在 `@zod.string`, (中文(简体) ), `@zod.number`, (中文(简体) ), `@zod.bigint`, (中文(简体) ), `@zod.date` 财务报告和审定财务报表 `@zod.custom`此外,你可以用在 enums 上与 `@zod.enum.array(...)` 和与《京都议定书》 `@zod.object.array(...)` 键。 您也可以向每个校验器添加自定义错误消息.

```prisma
model MyModel {
  id     Int     @id @default(autoincrement())
  string String[] /// @zod.string.array(.length(2, { message: "my message" }).min(1, { message: "my message" }).max(2, { message: "my message" }).nonempty({ message: "my message" }))
  number Int[] /// @zod.number.array(.length(2).min(1).max(2).nonempty())
  bigint BigInt[] /// @zod.bigint.array(.length(2).min(1).max(2).nonempty())
  date   DateTime[] /// @zod.date.array(.length(2).min(1).max(2).nonempty())
  custom String[] /// @zod.custom.use(z.string().refine(val => validator.isBIC(val)).transform(val => val.toUpperCase())).array(.length(2).min(1).max(2).nonempty())
  enum   MyEnum[] /// @zod.enum.array(.length(2).min(1).max(2).nonempty())
  object MyObject[] /// @zod.object.array(.length(2).min(1).max(2).nonempty())
}
```

上述模型计划将产生以下zod计划:

```ts
export const MyModel = z.object({
  id: z.number(),
  string: z
    .string()
    .array()
    .length(2, { message: 'my message' })
    .min(1, { message: 'my message' })
    .max(2, { message: 'my message' })
    .nonempty({ message: 'my message' }),
  number: z.number().array().length(2).min(1).max(2).nonempty(),
  bigint: z.bigint().array().length(2).min(1).max(2).nonempty(),
  date: z.date().array().length(2).min(1).max(2).nonempty(),
  custom: z
    .string()
    .refine((val) => validator.isBIC(val))
    .transform((val) => val.toUpperCase())
    .array()
    .length(2)
    .min(1)
    .max(2)
    .nonempty(),
  enum: MyEnumSchema.array().length(2).min(1).max(2).nonempty(),
})
```

## 缩写字段

可以通过使用 `@zod.custom.omit(["model", "input"])`。通过两个键时 `"model"` 财务报告和审定财务报表 `"input"` 字段在二者中被省略,生成的模型图和生成的输入类型(见下文示例)。 如果您想要在其中的某个计划中省略字段, 只需要提供匹配的密钥 。 您也可以不写 `"` 或者说 `'`。 。 。 .

```prisma
model MyModel {
  id           Int     @id @default(autoincrement())
  string       String? /// @zod.string.min(4).max(10)
  omitField    String? /// @zod.custom.omit([model, input])
  omitRequired String /// @zod.custom.omit([model, input])
}
```

上面的模型将生成以下的zod schemas(省略的密钥留在模型中,但被评论出来,这样你可以看到在查看zod schema时省略了哪些字段):

```ts
// MODEL TYPES
// ---------------------------------------

export const MyModelSchema = z.object({
  id: z.number(),
  string: z.string().min(4).max(10).nullish(),
  // omitted: omitField: z.string().nullish(),
  // omitted: omitRequired: z.string(),
})

// INPUT TYPES
// ---------------------------------------

export const MyModelCreateInputSchema: z.ZodType<
  Omit<PrismaClient.Prisma.MyModelCreateInput, 'omitField' | 'omitRequired'>
> = z
  .object({
    string: z.string().min(4).max(10).optional().nullable(),
    // omitted: omitField: z.string().optional().nullable(),
    // omitted: omitRequired: z.string(),
  })
  .strict()

export const MyModelUncheckedCreateInputSchema: z.ZodType<
  Omit<
    PrismaClient.Prisma.MyModelUncheckedCreateInput,
    'omitField' | 'omitRequired'
  >
> = z
  .object({
    id: z.number().optional(),
    string: z.string().min(4).max(10).optional().nullable(),
    // omitted: omitField: z.string().optional().nullable(),
    // omitted: omitRequired: z.string(),
  })
  .strict()

export const MyModelUpdateInputSchema: z.ZodType<
  Omit<PrismaClient.Prisma.MyModelUpdateInput, 'omitField' | 'omitRequired'>
> = z
  .object({
    string: z
      .union([
        z.string().min(4).max(10),
        z.lazy(() => NullableStringFieldUpdateOperationsInputSchema),
      ])
      .optional()
      .nullable(),
    // omitted: omitField: z.union([ z.string(),z.lazy(() => NullableStringFieldUpdateOperationsInputSchema) ]).optional().nullable(),
    // omitted: omitRequired: z.union([ z.string(),z.lazy(() => StringFieldUpdateOperationsInputSchema) ]).optional(),
  })
  .strict()

// AND SO ON...

// ARG TYPES
// ---------------------------------------

// To be compatible with the inputTypes the type of the `ArgSchema` is updated accordingly
export const MyModelCreateArgsSchema: z.ZodType<
  Omit<PrismaClient.Prisma.MyModelCreateArgs, 'data'> & {
    data:
      | z.infer<typeof MyModelCreateInputSchema>
      | z.infer<typeof MyModelUncheckedCreateInputSchema>
  }
> = z
  .object({
    select: MyModelSelectSchema.optional(),
    data: z.union([
      MyModelCreateInputSchema,
      MyModelUncheckedCreateInputSchema,
    ]),
  })
  .strict()
```

> 当a `required` 字段被省略 `create`, (中文(简体) ), `update`, (中文(简体) ), `createMany` 诸如来. 否则,打字会抱怨.

```ts
const appRouter = t.router({
  createMyModel: t.procedure
    .input(MyModelCreateArgsSchema) // field `omitRequired` is not included in `data`
    .query(({ input }) => {
      return prisma.myModel.create({
        ...input,
        data: {
          ...input.data,
          omitRequired: 'foo', // field needs to be added manually
        },
      })
    }),
})
```

## 校验错误

方便开发者体验生成器检查, 如果提供 `@zod.[key]` 可用于模型字段的相应类型。 它也检查是否 `@zod.[key].[validator]` 可用于指定的 `@zod.[key]`

### `Wrong zod type`

如果您使用验证键, 生成器会丢出错误 `@zod.string` 在错误的棱镜类型.

```prisma
model MyModel {
  string String /// @zod.string.min(3) -> valid - `string` can be used on `String`
  number Number /// @zod.string.min(3) -> invalid - `string` can not be used on `Number`
}
```

对于上述例子,错误消息看起来是这样的:

```bash
[@zod generator error]: Validator 'string' is not valid for type 'Int'. [Error Location]: Model: 'MyModel', Field: 'number'
```

生成器提供了准确的位置,出错之处和出错地点. 在有上百个模型和上百个自定义验证字符串的大棱镜图案中,这可以帮助.

### `Wrong validator`

如果您使用验证符, 生成器会丢出错误 `.min` 在错误的校验键上.

```prisma
model MyModel {
  number Int /// @zod.number.min(3) -> invalid - `min` can not be used on `number`
}
```

以上例子将产生以下错误:

```bash
[@zod generator error]: Validator 'min' is not valid for type 'Int'. [Error Location]: Model: 'MyModel', Field: 'number'.
```

### `Typo Errors`

如果您的校验字符串中包含打字符, 如

```prisma
model MyModel {
  string String /// @zod.string.min(3, { mussage: 'Must be at least 3 characters' })
}
```

生成器会投出以下错误:

```bash
[@zod generator error]: Could not match validator 'min' with validatorPattern
'.min(3, { mussage: 'Must be at least 3 characters' })'. Please check for typos! [Error Location]: Model: 'MyModel', Field: 'string'.
```

## 命名 Zod 计划

Zod 类型以生成的棱镜类型命名,并附有一个附件 `"Schema"` 绳子。 你只需要在棱镜函数上徘徊 你知道要导入哪种类型 这对Trpc v.10来说是这样的:

```ts
import {
  UserFindFirstArgsSchema,
  UserFindManyArgsSchema,
  UserFindUniqueArgsSchema,
} from './prisma/zod'

const appRouter = t.router({
  findManyUser: t.procedure.input(UserFindManyArgsSchema).query(({ input }) => {
    return prisma.user.findMany(input)
  }),
  findUniqueUser: t.procedure
    .input(UserFindUniqueArgsSchema)
    .query(({ input }) => {
      return prisma.user.findUnique(input)
    }),

  findFirstUser: t.procedure
    .input(UserFindFirstArgsSchema)
    .query(({ input }) => {
      return prisma.user.findFirst(input)
    }),
})
```

## 添加注释

您可以添加 [富人评论](https://www.prisma.io/docs/concepts/components/prisma-schema#comments) 以 jsDoc 的形式打印到您的模型和字段.

```prisma
/// comment line one
/// comment line two
model MyModel {
  id     Int     @id @default(autoincrement())
  /// comment before validator @zod.string.min(4).max(10)
  /// comment after validator
  string String?
}
```

上述模型将在从丰富的注释中取出验证器并添加到字符串字段时产生以下输出:

```ts
/**
 * comment line one
 * comment line two
 */
export const MyModelSchema = z.object({
  id: z.number(),
  /**
   * comment before validator
   * comment after validator
   */
  string: z.string().min(4).max(10).nullish(),
})
```

从注释中取出验证符并添加到字符串中

## 从 `zod-prisma`

两者之间有些不同 `zod-prisma` 财务报告和审定财务报表 `zod-prisma-types`。 。 。 . 下列章节应帮助您从 `zod-prisma` 改为 `zod-prisma-types`。 。 。 .

### 发电机选项

以下生成器选项来自 `zod-prisma` 没有以不同方式支持或执行 `zod-prisma-types`数字 :

#### `relationModel`

通过将以下选项传递给生成器,您可以生成包含模型所有关系的图案:

```prisma
generator zod {
  // ... other options
  createRelationValuesTypes = true
}
```

见 [`createRelationValuesTypes`](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-createrelationvaluestypes) 更多信息.

#### `modelCase`

该型号的外壳被固定在 `prisma schema` 而不能被改变。 这种方式,模型名称与混合外壳像 `MYModel` 生成时将按预期工作 `inputTypes`, (中文(简体) ), `enums`, (中文(简体) ), `argTypes`等 (中文(简体) ).

#### `modelSuffix`

模型后缀在 `zod-prisma-types` 固定为 `Schema` 而不能被改变.

#### `useDecimalJs`

`zod-prisma-types` 不支持 `decimal.js` 但使用棱镜提供的十进制执行来验证十进制类型。 见 [小数](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-decimal) 更多信息.

#### `imports`

截至版本 `2.0.0` 进口 `zod-prisma-types` 对模型定义有丰富的评论。 见 [自定义导入](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-custom-imports) 更多信息.

#### `prismaJsonNullability`

虚无 `zod-prisma-types` 处理不同。 见 [Json 无效值](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-json-null-values) 更多信息.

### 扩展 Zod 字段

`zod-prisma` 允许您使用自定义验证符扩展 Zod 字段。 这也可以 `zod-prisma-types` 编辑 `@zod.[key].[validator]` 语法. 不同的语法用于检查在特定棱镜类型上是否可以使用验证符. 见 [字段验证器](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-field-validators) 更多信息.

```prisma

// zod-prisma
model MyModel {
  string String /// @zod.min(3) -> valid - `string` can be used on `String`
  number Number /// @zod.min(3) -> valid - throws error only at runtime
}

//zod-prisma-types
model MyModel {
  string String /// @zod.string.min(3) -> valid - `string` can be used on `String`
  number Number /// @zod.string.min(3) -> invalid - throws error during generation
}
```

### 导入助手

您可以在生成器中导入自定义助手 。 请参看关于 [自定义进口](https://npmcn.com/package/%40electric-sql/prisma-generator/#readme-custom-imports) 更多信息.

## 常见问题

### @electric-sql/prisma-generator 是什么？

一个 Prisma 生成器,使用 Zod-prisma 类型生成的 schemas 创建 DB 描述对象\.

### 如何安装 @electric-sql/prisma-generator？

在项目目录运行 npm install @electric-sql/prisma-generator，或使用 pnpm add / yarn add / bun add。它还提供命令行工具 electric-sql-prisma-generator，可以用 npx electric-sql-prisma-generator 直接运行。

### @electric-sql/prisma-generator 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @electric-sql/prisma-generator 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @electric-sql/prisma-generator 可以商用吗？

@electric-sql/prisma-generator 使用 未声明 许可。package\.json 没有声明许可证。没有许可证的代码默认保留全部权利，商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括，不构成法律意见，请以许可原文为准。

### @electric-sql/prisma-generator 的下载量有多少？

根据 npm 官方下载统计，@electric-sql/prisma-generator 在 2026/10/14 – 2026/11/12 这 30 天内被下载 2,878 次，日均约 96 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @electric-sql/prisma-generator 还在维护吗？

最新版本 1\.1\.5 发布于 2024/05/07（2 年前）；至今共发布 10 个版本，其中过去 12 个月发布了 0 个；首次发布于 2023/07/18。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

