@arthurfiorette/prisma-kysely

中文文档
3.1.1发布于 2026/07/07MITES Module近 30 天下载 7.3万

Generate Kysely database types from a Prisma schema

原始使用文档
文档目录10 节
  1. Setup
  2. Banner Configuration
  3. Motivation
  4. Config
  5. Schema grouping
  6. PostgreSQL enum arrays
  7. Per-field type overrides
  8. Gotchas
  9. Contributions
  10. Shoutouts

Prisma Kysely


Hero image "Generate Kysely types directly from your Prisma schema"


Do you like Prisma's migration flow, schema language and DX but not the limitations of the Prisma Client? Do you want to harness the raw power of SQL without losing the safety of the TypeScript type system?

Enter prisma-kysely!

Setup

  1. Install prisma-kysely using your package manager of choice:

    bun add prisma-kysely
    
  2. Replace (or augment) the default client generator in your schema.prisma file with the following:

    generator kysely {
        provider = "prisma-kysely"
    
        // Optionally provide a destination directory for the generated file
        // and a filename of your choice
        output = "../src/db"
        fileName = "types.ts"
        // Optionally generate runtime enums to a separate file
        enumFileName = "enums.ts"
        // Optionally add content at the start of generated files (imports, pragmas, comments, etc.)
        banner = "import type { Decimal } from 'decimal.js';"
        // For multi-line, use Prisma's triple-quoted string syntax (see below)
    }
    
  3. Run prisma migrate dev or prisma generate and use your freshly generated types when instantiating Kysely!

Banner Configuration

The banner option allows you to add custom content at the start of generated files. This is particularly useful for importing custom types and libraries:

generator kysely {
    provider = "prisma-kysely"
    output = "../src/db"
    fileName = "types.ts"

    // Add custom imports for libraries you need in generated types
    banner = """
import type { Decimal } from 'decimal.js';
import { Big } from 'big.js';
import * as moment from 'moment';
import { v4 as uuid } from 'uuid';
import type { SomeType } from './custom-types';
"""
}

This will generate a file that starts with:

import type { Decimal } from "decimal.js";
import { Big } from "big.js";
import * as moment from "moment";
import { v4 as uuid } from "uuid";
import type { SomeType } from "./custom-types";

import type { ColumnType } from "kysely";
// ... rest of generated types

Motivation

Prisma's migration and schema definition workflow is undeniably great, and the typesafety of the Prisma client is top notch, but there comes a time in every Prisma user's life where the client becomes just a bit too limiting. Sometimes we just need to write our own multi table joins and squeeze that extra drop of performance out of our apps. The Prisma client offers two options: using their simplified query API or going all-in with raw SQL strings, sacrificing type safety.

This is where Kysely shines. Kysely provides a toolbox to write expressive, type-safe SQL queries with full autocompletion. The problem with Kysely though is that it's not super opinionated when it comes to schema definition and migration. What many users resort to is using something like Prisma to define the structure of their databases, and kysely-codegen to introspect their databases post-migration.

This package, prisma-kysely, is meant as a more integrated and convenient way to keep Kysely types in sync with Prisma schemas. After making the prerequisite changes to your schema file, it's just as convenient and foolproof as using Prisma's own client.

I've been using this combo for a few months now in tandem with Cloudflare's D1 for my private projects and Postgres at work. It's been a game-changer, and I hope it's just as useful for you! 😎

Config

KeyDescriptionDefault
outputThe directory where generated code will be saved
fileNameThe filename for the generated filetypes.ts
importExtensionThe extension to append to imports. E.g: ".js" or ".ts". Use "" to append nothing.""
enumFileNameThe filename for the generated enums. Omitting this will generate enums and files in the same file. Ignored when schemaGrouping is "namespace" or "exports", where grouped output owns enum placement.
camelCaseEnable support for Kysely's camelCase pluginfalse
exportWrappedTypesKysely wrapped types such as Selectable<Model> are also exported as described in the Kysely documentation. The exported types follow the naming conventions of the document.false
bannerContent to prepend to the start of generated file(s). Useful for custom imports, pragma directives (e.g., // @ts-nocheck), comments, or any other content. Supports single-line strings or multi-line via Prisma triple-quoted strings (""" ... """). The content is inserted verbatim at the top of the file(s).
readOnlyIdsUse Kysely's GeneratedAlways for @id fields with default values, preventing insert and update.false
enumArrayTypeControls generated types for Prisma enum arrays. Use "array" when your PostgreSQL driver parses enum-array OIDs into arrays, or "string" to type raw pg array literals such as {FOO,BAR}.array
[typename]TypeOverrideAllows you to override the resulting TypeScript type for any Prisma type. Useful when targeting a different environment than Node (e.g. WinterCG compatible runtimes that use UInt8Arrays instead of Buffers for binary types etc.) Check out the config validator for a complete list of options.
dbTypeNameAllows you to override the exported type with all tablesDB
schemaGroupingControls schema grouping. Use "none" for flat output, "namespace" for single-file export namespace Schema output, or "exports" to emit types/index.ts plus per-schema files re-exported with export * as Schema from "./schema".none
filterBySchemaWhen using multiple schemas, only include models and enums for the specified schema.false
defaultSchemaWhen using multiple schemas, declares which schema should stay ungrouped. In namespace mode it is not wrapped; in exports mode it remains in the index file.'public'

Schema grouping

schemaGrouping controls how multi-schema models and enums are grouped.

With schemaGrouping = "namespace", all grouped schemas stay in the configured types file:

export namespace Animals {
  export type Dog = {
    id: string;
  };
}

export type DB = {
  "animals.dogs": Animals.Dog;
};

With schemaGrouping = "exports" and fileName = "types.ts", output is written to types/index.ts with schema files beside it, such as types/animals.ts:

// types/index.ts
import type * as Animals from "./animals";

export * as Animals from "./animals";

export type DB = {
  "animals.dogs": Animals.Dog;
};
// types/animals.ts
export type Dog = {
  id: string;
};

If schema-file exports make autocomplete noisy next to the main namespaced DB types, prefer a monorepo setup where Prisma and DB types live in their own package. From that package, export only the main namespaced types your app should consume.

PostgreSQL enum arrays

PostgreSQL drivers such as pg do not automatically parse user-defined enum array OIDs. See node-pg-types#56. If your app registers enum-array parsers, keep the default enumArrayType = "array". Otherwise set enumArrayType = "string" to match raw pg array literals.

Install postgres-array if you use the parser below. Register parsers once, before running queries that read enum-array columns:

import { Kysely, PostgresDialect } from "kysely";
import pg from "pg";
import { parse as parsePostgresArray } from "postgres-array";

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });

// Registers enum array types.
// https://github.com/brianc/node-pg-types/issues/56#issuecomment-323223477
{
  const { rows } = await pool.query<{ typarray: number | string }>(
    `
    select t.typarray
    from pg_type as t
    inner join pg_namespace as n on n.oid = t.typnamespace
    where n.nspname not in ('pg_catalog', 'information_schema', 'pg_toast')
      and t.typtype = 'e'
      and t.typarray is not null
      and t.typarray != 0
  `
  );

  for (const row of rows) {
    pg.types.setTypeParser(Number(row.typarray), (value) =>
      value ? parsePostgresArray(value) : value
    );
  }
}

const db = new Kysely<DB>({
  dialect: new PostgresDialect({ pool }),
});

Per-field type overrides

In some cases, you might want to override a type for a specific field. This could be useful, for example, for constraining string types to certain literal values. Be aware though that this does not of course come with any runtime validation, and in most cases won't be guaranteed to match the actual data in the database.

That disclaimer aside, here's how it works: Add a @kyselyType(...) declaration to the Prisma docstring (deliniated using three slashes ///) for the field with your type inside the parentheses.

model User {
  id          String @id
  name        String

  /// @kyselyType('member' | 'admin')
  role        String
}

The parentheses can include any valid TS type declaration.

The output for the example above would be as follows:

export type User = {
  id: string;
  name: string;
  role: "member" | "owner";
};

Gotchas

Default values

By default (no pun intended) the Prisma Query Engine uses JS based implementations for certain default values, namely: uuid() and cuid(). This means that they don't end up getting defined as default values on the database level, and end up being pretty useless for us.

Prisma does provide a nice solution to this though, in the form of dbgenerated(). This allows us to use any valid default value expression that our database supports:

model PostgresUser {
   id    String @id @default(dbgenerated("gen_random_uuid()"))
}

model SQLiteUser {
   id    String @id @default(dbgenerated("(uuid())"))
}

Check out the Prisma Docs for more info.

Contributions

OMG you actually want to contribute? I'm so thankful! 🙇‍♂️

Here's everything you need to do (let me know if something's missing...)

  1. Fork and pull the repository
  2. Run bun install and bun dev to start tsc in watch mode.
  3. Make changes to the source code
  4. Test your changes by creating prisma/schema.prisma, running bun prisma generate and checking the output in prisma/types.ts. The provider must be set as follows to reference the dev build:
    generator kysely {
        provider = "node ./dist/bin.js"
    }
    
  5. Create a pull request! If your changes make sense, I'll try my best to review and merge them quickly.

I'm not 100% sure the type maps are correct for every dialect, so any and all contributions on that front would be greatly appreciated. The same goes for any bug you come across or improvement you can think of.

Shoutouts

  • I wouldn't have made this library if I hadn't used Robin Blomberg's amazing Kysely Codegen. For anyone that isn't using Prisma for migrations I wholeheartedly recommend his package.
  • The implicit many-to-many table generation code is partly inspired by and partly stolen from prisma-dbml-generator. Many-too-many thanks to them!
  • Igal Klebanov (@igalklebanov) and Jökull Sólberg (@jokull) for being this library's main proponents on Twitter!
  • The authors and maintainers of Kysely ❤️‍🔥
+ Boyce-Codd gang unite! 💽

版本与发布记录

@arthurfiorette/prisma-kysely 共发布 8 个版本,首次发布于 2025/01/11;过去 12 个月发布了 1 个版本。

版本发布日期距今
3.1.1latest2026/07/074 个月前
2.2.02025/07/211.3 年前
2.1.02025/06/261.4 年前
2.0.12025/06/021.4 年前
2.0.02025/06/021.4 年前
1.10.12025/03/061.7 年前

关于 @arthurfiorette/prisma-kysely 的常见问题

@arthurfiorette/prisma-kysely 是什么?

Generate Kysely database types from a Prisma schema

如何安装 @arthurfiorette/prisma-kysely?

在项目目录运行 npm install @arthurfiorette/prisma-kysely,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:prisma(>=7.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。它还提供命令行工具 prisma-kysely,可以用 npx prisma-kysely 直接运行。

@arthurfiorette/prisma-kysely 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/arthurfiorette__prisma-kysely 是否存在。

@arthurfiorette/prisma-kysely 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@arthurfiorette/prisma-kysely 可以商用吗?

@arthurfiorette/prisma-kysely 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@arthurfiorette/prisma-kysely 的下载量有多少?

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

@arthurfiorette/prisma-kysely 还在维护吗?

最新版本 3.1.1 发布于 2026/07/07(4 个月前);至今共发布 8 个版本,其中过去 12 个月发布了 1 个;首次发布于 2025/01/11。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。