---
title: 使用 Kysely
sidebar_label: Kysely
---

来源：https://mikro-orm.io/docs/kysely

MikroORM 与 [Kysely](https://kysely.dev/)（一个类型安全的 SQL 查询构建器）提供了一等集成。通过该集成，你可以直接从 `EntityManager` 获取一个已配置好的 Kysely 实例，利用 MikroORM 的元数据来驱动 Kysely 的查询转换与类型推断。

这让你可以编写更底层的 SQL 查询，同时保持类型安全，并复用 MikroORM 中定义的实体关联与钩子。该集成适用于所有实体定义风格——装饰器、`EntitySchema` 以及 `defineEntity`。

<a id="getting-a-kysely-instance"></a>
## 获取 Kysely 实例

你可以通过 `em.getKysely()` 方法获取 Kysely 实例：

```ts
const kysely = orm.em.getKysely();
```

默认情况下，这会给你一个不带 MikroORM 插件的原始 Kysely 实例。要启用诸如实体名/属性名映射、钩子处理以及值转换等 MikroORM 感知特性，请传入一个配置对象：

```ts
const kysely = orm.em.getKysely({
  tableNamingStrategy: 'entity',
  columnNamingStrategy: 'property',
  processOnCreateHooks: true,
  processOnUpdateHooks: true,
  convertValues: true,
});
```

这些选项在下文的[插件选项](#plugin-options)章节中有详细说明。

<a id="transaction-context"></a>
## 事务上下文

`getKysely()` 会自动使用 EntityManager 当前的事务上下文。当在 `em.transactional(...)` 内部（或 `em.begin()` 之后）调用时，返回的 Kysely 实例会绑定到正在进行的事务，因此任何通过 Kysely 自身的 `.execute()` / `.executeTakeFirst*()` 执行的查询都会参与该事务，并随它一起回滚。

```ts
await orm.em.transactional(async em => {
  const kysely = em.getKysely({ tableNamingStrategy: 'entity', convertValues: true });

  // 在事务内部运行
  await kysely.insertInto('Doc').values({ title: 't', content: 'hello' }).execute();

  throw new Error('boom'); // 回滚上面的插入
});
```

如果你需要一个**不**绑定当前事务的 Kysely 实例——例如在事务块内部从连接池读取数据——请先 fork EntityManager。被 fork 出来的 EM 没有事务上下文，因此 `getKysely()` 会回退到连接池客户端：

```ts
await orm.em.transactional(async em => {
  // 绑定到当前事务
  await em.getKysely().selectFrom('user').selectAll().execute();

  // 绑定到连接池，在事务之外运行
  await em.fork().getKysely().selectFrom('audit_log').selectAll().execute();
});
```

`type` 选项（`'read'` / `'write'`）只在事务之外才会生效——在事务内部，连接已经被固定了。

<a id="using-entity-and-property-names-in-queries"></a>
## 在查询中使用实体名与属性名

插件最有用的特性之一，是可以用你的实体名与属性名（而不是原始的表名与列名）来编写 Kysely 查询。无论你如何定义实体——装饰器、`EntitySchema` 还是 `defineEntity`——这都适用。

```ts
@Entity()
class UserProfile {

  [EntityName]?: 'UserProfile';

  @PrimaryKey()
  id!: number;

  @Property()
  firstName!: string; // 映射到 'first_name' 列

  @Property()
  lastName!: string; // 映射到 'last_name' 列

}

const kysely = orm.em.getKysely({
  tableNamingStrategy: 'entity',
  columnNamingStrategy: 'property',
});

const users = await kysely
  .selectFrom('UserProfile') // 实体名，而不是表名
  .select(['firstName', 'lastName']) // 属性名，而不是列名
  .where('firstName', '=', 'John')
  .execute();

// 生成的 SQL：select "first_name", "last_name" from "user_profile" where "first_name" = ?

// 结果会被自动映射回属性名
console.log(users[0].firstName); // 'John'
```

插件会在查询编译时把实体名翻译为表名、把属性名翻译为列名，因此你可以编写与 TypeScript 代码一致、而非与数据库 schema 一致的查询。

<a id="type-safety"></a>
## 类型安全

<a id="automatic-inference-with-defineentity"></a>
### 使用 `defineEntity` 自动推断

当你使用 `defineEntity` 定义实体时，`getKysely()` 会自动从实体元数据推断出完整的数据库类型——表名、列类型、可空性以及关联关系都从你的属性定义中派生而来：

```ts
import { MikroORM, defineEntity, p } from '@mikro-orm/core';

const User = defineEntity({
  name: 'User',
  tableName: 'users',
  properties: {
    name: p.string().primary(),
    email: p.string().nullable(),
  },
});

const orm = new MikroORM({
  dbName: ':memory:',
  entities: [User],
});

// getKysely() 会自动推断表结构
const kysely = orm.em.getKysely();

// 完全类型安全：TypeScript 会自动补全 'users' 表及其列
const result = await kysely
  .selectFrom('users')
  .selectAll()
  .where('email', 'is not', null)
  .execute();
```

<a id="automatic-inference-with-decorator-entities"></a>
### 使用装饰器实体自动推断

对于基于装饰器的实体，你可以通过添加 `[EntityName]` 符号属性来启用自动类型推断。它会在类型层面告诉 `getKysely()` 实体名，使其能够从类属性推断表与列的类型：

```ts
import { Entity, PrimaryKey, Property } from '@mikro-orm/decorators/legacy';
import { EntityName, MikroORM } from '@mikro-orm/sqlite';

@Entity()
class UserProfile {

  [EntityName]?: 'UserProfile';

  @PrimaryKey()
  id!: number;

  @Property()
  firstName!: string;

  @Property()
  lastName!: string;

}

const orm = await MikroORM.init({
  dbName: ':memory:',
  // 必须显式传入实体类，类型推断才能生效
  entities: [UserProfile],
});

// getKysely() 会从类属性推断表
const kysely = orm.em.getKysely({
  columnNamingStrategy: 'property',
});

// TypeScript 知道 'user_profile' 表以及 id、firstName、lastName 列
const result = await kysely
  .selectFrom('user_profile')
  .select(['id', 'firstName', 'lastName'])
  .execute();
```

`[EntityName]` 符号属性是必需的——没有它，`getKysely()` 无法从类引用中把实体名推断为字符串字面量类型。这与 `[EntityRepositoryType]` 对自定义仓库类型的作用类似。

列类型直接从类实例属性推断而来。表名遵循配置的命名策略（默认是下划线风格）。当使用 `tableNamingStrategy: 'entity'` 时，实体名（`'UserProfile'`）会在查询中原样使用。

> 要实现自动类型推断，必须在 `entities` 数组中显式传入实体类（而不是文件夹路径）。这种方式直接使用类属性类型，不支持细粒度的列名映射（例如自定义 `fieldName`）——需要这种控制粒度时请使用 `defineEntity`。

<a id="manual-type-declarations"></a>
### 手动类型声明

对于基于装饰器或 `EntitySchema` 的实体，你也可以为 `getKysely()` 提供手动的数据库类型：

```ts
// 定义与你的实体相匹配的数据库类型
interface Database {
  user_profile: {
    id: number;
    first_name: string;
    last_name: string;
  };
  post: {
    id: number;
    title: string;
    author_id: number;
  };
}

// 把类型传给 getKysely() 以获得完整的类型安全
const kysely = orm.em.getKysely<Database>();

const user = await kysely
  .selectFrom('user_profile')
  .select(['id', 'first_name'])
  .executeTakeFirst();
```

当使用 `columnNamingStrategy: 'property'` 时，请改用属性名来定义接口：

```ts
interface Database {
  user_profile: {
    id: number;
    firstName: string;
    lastName: string;
  };
}

const kysely = orm.em.getKysely<Database>({
  columnNamingStrategy: 'property',
});
```

<a id="mixing-inferred-and-manual-types"></a>
### 混用推断类型与手动类型

你可以把 `InferKyselyTable`（用于 `defineEntity` 实体）与手动类型声明（用于其他表或视图）结合起来：

```ts
import { InferKyselyTable } from '@mikro-orm/postgresql';

const pluginOptions = {
  tableNamingStrategy: 'entity',
  convertValues: true,
} as const;

// 为数据库视图或没有 defineEntity 定义的表手动声明类型
interface ViewStatsTable {
  view_id: number;
  view_count: number;
}

interface Database {
  User: InferKyselyTable<typeof User, typeof pluginOptions>;
  Post: InferKyselyTable<typeof Post, typeof pluginOptions>;
  view_stats: ViewStatsTable;
}

const kysely = orm.em.getKysely<Database>(pluginOptions);

const user = await kysely.selectFrom('User').selectAll().executeTakeFirst();
const stats = await kysely.selectFrom('view_stats').selectAll().executeTakeFirst();
```

<a id="generating-entity-exports-with-the-cli"></a>
### 使用 CLI 生成实体导出

对于实体较多的项目，在 ORM 配置中维护一个手动的 `entities` 数组可能既繁琐又容易出错。`discovery:export` CLI 命令会扫描你的实体源文件，并生成一个 TypeScript barrel 文件，其中导出：

- 一个用于 ORM 配置的 `entities` 数组
- 一个 `Database` 类型——即实体元组，可在任何接受实体元组的地方使用（例如 `MikroORM<Driver, EM, Database>`）
- 一个 `EntityManager` 类型——用于 DI 场景、绑定了驱动且感知实体的 `EntityManager` 别名

```bash
npx mikro-orm discovery:export
```

该命令会从你的 ORM 配置（`entitiesTs` 或 `entities`）读取实体路径，发现所有实体类与 schema，并生成类似下面这样的文件：

```ts
// This file was generated by MikroORM CLI. Do not edit manually.
// Re-run `mikro-orm discovery:export` to update.

import { Author } from './entities/Author.js';
import { BookSchema } from './entities/Book.js';
import type { EntityManager as DriverEntityManager } from '@mikro-orm/postgresql';

export const entities = [
  Author,
  BookSchema,
] as const;

export type Database = typeof entities;

export type EntityManager = DriverEntityManager & { '~entities': Database };
```

在你的 ORM 配置中使用生成的 `entities` 数组：

```ts
import { entities } from './entities.generated';

export default defineConfig({ entities });
```

在 DI / 框架场景（例如 NestJS）中，EntityManager 原本会丢失其实体元组，此时请导入生成的 `EntityManager`。生成的文件同时以类型（通过幻影 `'~entities'` 接枝携带实体元组）和 `const`（重新导出驱动真正的 EM 类）的形式导出它——因此它既可充当 Nest 的 DI token，也可作为参数的类型标注。驱动已经由代码生成固定——无需再填写驱动泛型——并且 `em.getKysely(opts)` 对数据库结构与调用处的插件选项都保持完整的类型推断：

```ts
import { EntityManager } from './entities.generated';

@Injectable()
export class ArticleService {
  constructor(private readonly em: EntityManager) {}

  list() {
    // 物理名/下划线名
    return this.em.getKysely().selectFrom('article').selectAll().execute();
  }

  listByEntityName() {
    // 以实体命名的表、以属性命名的列 ——由运行时选项推断
    return this.em
      .getKysely({ tableNamingStrategy: 'entity', columnNamingStrategy: 'property' })
      .selectFrom('Article')
      .selectAll()
      .execute();
  }
}
```

<a id="using-a-custom-entitymanager-subclass"></a>
#### 使用自定义 `EntityManager` 子类

生成的 `EntityManager` 重新导出的是驱动自带的 EM。如果你扩展了它（参见[扩展 `EntityManager`](./10-entity-manager.md#extending-entitymanager)）并希望你的子类也具备同样的实体感知类型，请不要改动生成的文件，而是在旁边写一个很小的包装器，把生成的 `Database` 元组接枝到你自己的类上：

```ts title="custom-em.ts"
import { entities, type Database } from './entities.generated.js';
import { MyEntityManager } from './MyEntityManager.js';

export { entities };
export type EntityManager = MyEntityManager & { '~entities': Database };
export const EntityManager = MyEntityManager;
```

然后在你的 DI 绑定与服务中，从 `./custom-em` 而不是 `./entities.generated` 导入 `EntityManager`。生成的 barrel 文件保持纯机械式（因此重新运行 `discovery:export` 永远不会覆盖你自定义 EM 的胶水代码），并且 `em.getKysely(opts)` 透过子类依然保持完整的类型推断。

<a id="using-it-in-custom-repositories"></a>
#### 在自定义仓库中使用

仓库的 `em` 属性被类型化为普通的驱动 EM，因此 `this.em.getKysely()` 不带任何实体信息。用生成的 `EntityManager` 类型重新声明它，即可在你的[自定义仓库](./14-repositories.md#custom-repository)中获得同样的推断：

```ts title="BookRepository.ts"
import { EntityRepository } from '@mikro-orm/postgresql';
import type { EntityManager } from './entities.generated.js';
import { Book } from './Book.entity.js';

export class BookRepository extends EntityRepository<Book> {
  declare protected readonly em: EntityManager;

  findTitlesWithAuthors() {
    return this.em
      .getKysely()
      .selectFrom('book')
      .innerJoin('author', 'author.id', 'book.author_id')
      .select(['book.title', 'author.first_name'])
      .execute();
  }
}
```

`declare` 修饰符只改变类型，没有运行时效果。由于接枝的类型携带了完整的实体元组，所有表都可用（而不仅是该仓库对应的那张），因此连接也能通过类型检查。

<a id="command-options"></a>
#### 命令选项

| Flag | Type | Description |
|------|------|-------------|
| `-p, --path` | `string[]` | 实体源文件的 glob 模式 |
| `-o, --out` | `string` | 输出文件路径（默认：ORM 配置旁边） |
| `-d, --dump` | `boolean` | 打印到标准输出而不是写入文件 |

如果未提供 `--path`，该命令会从你配置的 `entitiesTs`（优先）或 `entities` 数组中提取文件夹/glob 路径。在把配置切换为使用生成的 barrel 文件（其中包含的是实体引用而非路径）之后，你需要显式传入 `--path` 才能重新运行该命令：

```bash
npx mikro-orm discovery:export --path './src/entities/*.ts'
```

<a id="plugin-options"></a>
## 插件选项

当你把配置对象传给 `getKysely()` 时，返回的实例会包含 `MikroKyselyPlugin`。该插件会拦截 Kysely 的查询编译与结果处理，以支持 MikroORM 特有的功能。

<a id="tablenamingstrategy"></a>
### `tableNamingStrategy`

控制你在 Kysely 查询中如何引用表。

- `'table'`（**默认**）：使用数据库中实际的表名（例如 `user_profiles`）。这是 Kysely 的标准行为。
- `'entity'`：使用实体名（例如 `UserProfile`）。插件会在生成 SQL 之前把它转换为对应的表名。

```ts
// 假设实体名为 'User'，数据库表名为 'users'

// 默认（tableNamingStrategy: 'table'）
await kysely.selectFrom('users').selectAll().execute();

// 使用实体名策略（tableNamingStrategy: 'entity'）
await kysely.selectFrom('User').selectAll().execute();
// 生成的 SQL：select * from "users"
```

<a id="columnnamingstrategy"></a>
### `columnNamingStrategy`

控制你在 Kysely 查询中如何引用列，以及结果如何被映射。

- `'column'`（**默认**）：使用数据库中实际的列名（例如 `first_name`）。
- `'property'`：使用实体属性名（例如 `firstName`）。插件会在生成 SQL 时把属性名转换为列名，并在返回结果中把列名映射回属性名。

```ts
const kysely = orm.em.getKysely({ columnNamingStrategy: 'property' });

const users = await kysely
  .selectFrom('user')
  .select(['firstName', 'lastName']) // 属性名
  .where('firstName', '=', 'John')
  .execute();

// 生成的 SQL：select "first_name", "last_name" from "user" where "first_name" = ?

// 结果会被自动映射回属性名
console.log(users[0].firstName); // 'John'
```

<a id="processoncreatehooks"></a>
### `processOnCreateHooks`

布尔值，默认为 `false`。

启用后，`INSERT` 查询会自动处理定义在实体属性上的 `onCreate` 钩子。如果你的插入数据缺少某些配置了 `onCreate` 的属性（例如 `createdAt`），插件会自动生成并把它们加入查询。

```ts
// 带 onCreate 钩子的实体属性：
// @Property({ onCreate: () => new Date() })
// createdAt!: Date;

const kysely = orm.em.getKysely({ processOnCreateHooks: true });

// 插入时不带 createdAt ——它会被自动添加
await kysely.insertInto('user').values({ name: 'John' }).execute();

// 生成的 SQL 会自动包含 created_at
// insert into "user" ("name", "created_at") values (?, ?)
```

<a id="processonupdatehooks"></a>
### `processOnUpdateHooks`

布尔值，默认为 `false`。

启用后，`UPDATE` 查询会自动处理定义在实体属性上的 `onUpdate` 钩子。例如自动更新 `updatedAt` 时间戳字段。

```ts
// 带 onUpdate 钩子的实体属性：
// @Property({ onUpdate: () => new Date() })
// updatedAt!: Date;

const kysely = orm.em.getKysely({ processOnUpdateHooks: true });

await kysely
  .updateTable('user')
  .set({ name: 'Johnny' })
  .where('id', '=', 1)
  .execute();

// 生成的 SQL 会自动包含 updated_at
// update "user" set "name" = ?, "updated_at" = ? where "id" = ?
```

<a id="convertvalues"></a>
### `convertValues`

布尔值，默认为 `false`。

启用后，插件会使用 MikroORM 的类型系统来转换查询参数与结果值。这对于处理驱动特有的类型（例如 SQLite 中以数字/字符串存储的 Date）或自定义类型非常重要。

- **输入转换**：把 JavaScript 对象（例如 `Date`）转换为数据库支持的格式。
- **输出转换**：把数据库返回的原始值转换回 JavaScript 对象或自定义类型。

```ts
const kysely = orm.em.getKysely({ convertValues: true });

// 1. 输入转换：Date 对象会被自动处理
await kysely
  .insertInto('user')
  .values({
    name: 'John',
    bornAt: new Date('1990-01-01') // 自动转换为数据库格式
  })
  .execute();

// 2. 输出转换：读取时自动转换回 Date 对象
const user = await kysely
  .selectFrom('user')
  .selectAll()
  .executeTakeFirst();

console.log(user.bornAt instanceof Date); // true
```
