---
title: 与 CockroachDB 一起使用
---

来源：https://mikro-orm.io/docs/usage-with-cockroachdb

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

MikroORM 通过 `@mikro-orm/postgresql` 驱动支持 [CockroachDB](https://www.cockroachlabs.com/)。CockroachDB 与 PostgreSQL 线协议兼容，因此大多数 MikroORM 特性都能开箱即用。本指南介绍配置方式以及你需要了解的关键差异。

<a id="installation"></a>
## 安装

安装 PostgreSQL 驱动即可——不需要单独的 CockroachDB 包：

```bash npm2yarn
npm install @mikro-orm/core @mikro-orm/postgresql
```

<a id="configuration"></a>
## 配置

一个最小的 CockroachDB 配置：

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

export default defineConfig({
  entities: ['./dist/entities'],
  entitiesTs: ['./src/entities'],
  dbName: 'my_database',
  host: 'localhost',
  port: 26257,
  user: 'root',
  password: '',
});
```

CockroachDB 默认使用端口 `26257`，而不是 PostgreSQL 的 `5432`。

<a id="cockroachdb-cloud-ssl"></a>
### CockroachDB Cloud（SSL）

CockroachDB Cloud 要求使用 SSL。请通过 `driverOptions` 传入 CA 证书，它会直接映射到 `pg.Pool` 的选项：

```ts
import { defineConfig } from '@mikro-orm/postgresql';
import { readFileSync } from 'node:fs';

export default defineConfig({
  dbName: 'my_database',
  host: 'your-cluster.cockroachlabs.cloud',
  port: 26257,
  user: 'your-user',
  password: 'your-password',
  driverOptions: {
    ssl: {
      ca: readFileSync('./path/to/ca-cert.crt', 'utf8'),
    },
  },
});
```

<a id="primary-keys"></a>
## 主键

CockroachDB 的 `serial` 类型使用 `unique_rowid()`，它会生成 64 位整数。与 PostgreSQL 的 `serial`（带序列的 `int4`）不同，这些是 `int8` 值，会超出 JavaScript 的 `Number.MAX_SAFE_INTEGER`。`pg` 驱动会把它们以字符串形式返回，因此你需要相应地标注主键类型。

<a id="option-1-uuid-primary-keys-recommended"></a>
### 方案 1：UUID 主键（推荐）

为了在各个节点间获得最佳的数据分布，CockroachDB 推荐使用 UUID 主键。使用 `serial`/自增键可能导致写入热点。

<Tabs
  groupId="entity-def"
  defaultValue="define-entity"
  values={[
    {label: 'defineEntity', value: 'define-entity'},
    {label: 'Decorators', value: 'decorators'},
  ]
  }>
  <TabItem value="define-entity">

```ts
const Author = defineEntity({
  name: 'Author',
  properties: {
    id: p.uuid().primary(),
    name: p.string(),
  },
});
```

  </TabItem>
  <TabItem value="decorators">

```ts
@Entity()
class Author {

  @PrimaryKey({ type: 'uuid' })
  id: string = v4();

  @Property()
  name!: string;

}
```

  </TabItem>
</Tabs>

<a id="option-2-serial-with-biginttype"></a>
### 方案 2：配合 `BigIntType` 使用 Serial

如果你更偏好自增风格的键，请使用 `BigIntType` 把 `serial` 值映射为 `string` 或 `bigint`：

<Tabs
  groupId="entity-def"
  defaultValue="define-entity"
  values={[
    {label: 'defineEntity', value: 'define-entity'},
    {label: 'Decorators', value: 'decorators'},
  ]
  }>
  <TabItem value="define-entity">

```ts
const Author = defineEntity({
  name: 'Author',
  properties: {
    id: p.bigint('string').primary(),
    name: p.string(),
  },
});
```

或使用原生的 `bigint`：

```ts
const Author = defineEntity({
  name: 'Author',
  properties: {
    id: p.bigint().primary(),
    name: p.string(),
  },
});
```

  </TabItem>
  <TabItem value="decorators">

```ts
@Entity()
class Author {

  @PrimaryKey({ type: new BigIntType('string') })
  id!: string;

}
```

或使用原生的 `bigint`：

```ts
@Entity()
class Author {

  @PrimaryKey()
  id!: bigint;

}
```

  </TabItem>
</Tabs>

> 唯一**不**可行的是 `@PrimaryKey() id!: number` / `p.integer().primary()`——CockroachDB 的 `serial` 值对 JavaScript 的 `number` 类型来说太大了。

<a id="integer-columns"></a>
## 整数列

CockroachDB 在内部把所有整数类型（`int2`、`int4`、`int8`）都映射为 64 位整数。`pg` 驱动会把超出 `Number.MAX_SAFE_INTEGER` 的值以字符串形式返回。对于 `age` 或 `count` 这类常规整数列，取值会落在安全范围内，用 `number` 类型即可正常工作。

<a id="schema-generator"></a>
## Schema 生成器

Schema 生成器可以与 CockroachDB 一起工作。你可以照常使用 `orm.schema.create()`、`orm.schema.update()` 与 `orm.schema.drop()`。

<a id="clearing-the-database"></a>
### 清空数据库

CockroachDB 不支持 `TRUNCATE ... RESTART IDENTITY`。要使用 `orm.schema.clear()`，请传入 `truncate: false` 以回退到有序的 `DELETE` 语句：

```ts
await orm.schema.clear({ truncate: false });
```

<a id="schema-diffing"></a>
### Schema 差异比较

由于 CockroachDB 的目录实现不同，schema 内省可能会报告一些与 PostgreSQL 相比的细微差异。如果你在 `orm.schema.getUpdateSchemaSQL()` 中看到意料之外的差异，请在应用前仔细核对。

<a id="supported-features"></a>
## 受支持的特性

以下特性已经过测试，可与 CockroachDB 一起工作：

- CRUD 操作（增、查、改、删）
- 关联：ManyToOne、OneToMany、ManyToMany、OneToOne
- 自引用关联
- 填充提示与加载策略（SELECT_IN、JOINED）
- 带条件、排序与分页的 QueryBuilder
- 带 limit/offset 的 `findAndCount`
- 事务与事务回滚
- 批量插入
- Upsert（`em.upsert()`）
- JSONB 列
- 数组列（例如 `text[]`）
- UUID 主键
- Serial 主键（配合 `BigIntType` 或 `bigint`）
- Schema 生成器（create、update、drop）
- 迁移

<a id="known-limitations"></a>
## 已知限制

| Feature | Status | Notes |
|---------|--------|-------|
| `serial`/`bigserial` 主键 | 使用 `BigIntType` 或 UUID | CockroachDB 的 `unique_rowid()` 返回 `int8`；`number` 类型不可行 |
| 整数类型 | 全部映射为 `int8` | 小值可用 `number`；大值需要 `bigint` 或 `string` |
| `TRUNCATE ... RESTART IDENTITY` | 不支持 | 请改用 `orm.schema.clear({ truncate: false })` |
| `polygon`、`line`、`path` 类型 | 不支持 | CockroachDB 不支持 PostgreSQL 的几何类型 |
| 全文检索（`tsvector`） | 不支持 | CockroachDB 有自己的[全文检索](https://www.cockroachlabs.com/docs/stable/full-text-search) |
| 原生 PostgreSQL 枚举 | 有限 | 请改用 check 约束 |
| 物化视图 | 不支持 | CockroachDB 不支持 `CREATE MATERIALIZED VIEW` |
| 可延迟约束 | 不支持 | CockroachDB 不支持 `INITIALLY DEFERRED` |

<a id="full-example"></a>
## 完整示例

<Tabs
  groupId="entity-def"
  defaultValue="define-entity"
  values={[
    {label: 'defineEntity', value: 'define-entity'},
    {label: 'Decorators', value: 'decorators'},
  ]
  }>
  <TabItem value="define-entity">

```ts
const Author = defineEntity({
  name: 'Author',
  properties: {
    id: p.uuid().primary(),
    name: p.string(),
    email: p.string(),
    books: () => p.oneToMany(Book).mappedBy('author'),
  },
});

const Book = defineEntity({
  name: 'Book',
  properties: {
    id: p.uuid().primary(),
    title: p.string(),
    author: () => p.manyToOne(Author),
  },
});

const orm = await MikroORM.init({
  entities: [Author, Book],
  dbName: 'my_database',
  host: 'localhost',
  port: 26257,
  user: 'root',
  password: '',
});

await orm.schema.update();

const em = orm.em.fork();
const author = em.create(Author, { name: 'John', email: 'john@example.com' });
em.create(Book, { title: 'My Book', author });
await em.flush();

const books = await em.find(Book, {}, { populate: ['author'] });
console.log(books[0].author.name); // 'John'

await orm.close();
```

  </TabItem>
  <TabItem value="decorators">

```ts
@Entity()
class Author {

  @PrimaryKey({ type: 'uuid' })
  id: string = v4();

  @Property()
  name!: string;

  @Property()
  email!: string;

  @OneToMany(() => Book, book => book.author)
  books = new Collection<Book>(this);

}

@Entity()
class Book {

  @PrimaryKey({ type: 'uuid' })
  id: string = v4();

  @Property()
  title!: string;

  @ManyToOne(() => Author)
  author!: Author;

}

const orm = await MikroORM.init({
  entities: [Author, Book],
  driver: PostgreSqlDriver,
  metadataProvider: ReflectMetadataProvider,
  dbName: 'my_database',
  host: 'localhost',
  port: 26257,
  user: 'root',
  password: '',
});

await orm.schema.update();

const em = orm.em.fork();
const author = em.create(Author, { name: 'John', email: 'john@example.com' });
em.create(Book, { title: 'My Book', author });
await em.flush();

const books = await em.find(Book, {}, { populate: ['author'] });
console.log(books[0].author.name); // 'John'

await orm.close();
```

  </TabItem>
</Tabs>
