# 多数据源、数据库、模式与复制配置

> 英文标题：Multiple data sources, databases, schemas and replication setup
> 官网原文：https://typeorm.io/docs/data-source/multiple-data-sources
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 50 块

---

<!-- EN -->
# Multiple data sources, databases, schemas and replication setup

<!-- ZH -->
# 多数据源、数据库、模式与复制配置

<!-- EN -->
## Using multiple data sources

<!-- ZH -->
## 使用多个数据源

<!-- EN -->
To use multiple data sources connected to different databases, simply create multiple DataSource instances:

<!-- ZH -->
要使用连接到不同数据库的多个数据源，只需创建多个 DataSource 实例：

<!-- EN -->
```typescript
import { DataSource } from "typeorm"

const db1DataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "root",
    password: "admin",
    database: "db1",
    entities: [__dirname + "/entities/*{.js,.ts}"],
    synchronize: true,
})

const db2DataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "root",
    password: "admin",
    database: "db2",
    entities: [__dirname + "/entities/*{.js,.ts}"],
    synchronize: true,
})
```

<!-- ZH -->
```typescript
import { DataSource } from "typeorm"

const db1DataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "root",
    password: "admin",
    database: "db1",
    entities: [__dirname + "/entities/*{.js,.ts}"],
    synchronize: true,
})

const db2DataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "root",
    password: "admin",
    database: "db2",
    entities: [__dirname + "/entities/*{.js,.ts}"],
    synchronize: true,
})
```

<!-- EN -->
## Using multiple databases within a single data source

<!-- ZH -->
## 在单个数据源中使用多个数据库

<!-- EN -->
To use multiple databases in a single data source, you can specify database name per-entity:

<!-- ZH -->
要在单个数据源中使用多个数据库，你可以为每个实体指定数据库名：

<!-- EN -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity({ database: "secondDB" })
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    firstName: string

    @Column()
    lastName: string
}
```

<!-- ZH -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity({ database: "secondDB" })
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    firstName: string

    @Column()
    lastName: string
}
```

<!-- EN -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity({ database: "thirdDB" })
export class Photo {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    url: string
}
```

<!-- ZH -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity({ database: "thirdDB" })
export class Photo {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    url: string
}
```

<!-- EN -->
`User` entity will be created inside `secondDB` database and `Photo` entity inside `thirdDB` database. All other entities will be created in a default database defined in the data source options.

<!-- ZH -->
`User` 实体会被创建在 `secondDB` 数据库中，`Photo` 实体会被创建在 `thirdDB` 数据库中。所有其他实体都会创建在数据源选项中定义的默认数据库里。

<!-- EN -->
If you want to select data from a different database you only need to provide an entity:

<!-- ZH -->
如果你想从另一个数据库中查询数据，只需要提供一个实体：

<!-- EN -->
```typescript
const users = await dataSource
    .createQueryBuilder()
    .select()
    .from(User, "user")
    .addFrom(Photo, "photo")
    .andWhere("photo.userId = user.id")
    .getMany() // userId is not a foreign key since its cross-database request
```

<!-- ZH -->
```typescript
const users = await dataSource
    .createQueryBuilder()
    .select()
    .from(User, "user")
    .addFrom(Photo, "photo")
    .andWhere("photo.userId = user.id")
    .getMany() // userId 不是外键，因为这是跨数据库请求
```

<!-- EN -->
This code will produce following SQL query (depend on database type):

<!-- ZH -->
这段代码会生成如下 SQL 查询（取决于数据库类型）：

<!-- EN -->
```sql
SELECT * FROM "secondDB"."user" "user", "thirdDB"."photo" "photo"
    WHERE "photo"."userId" = "user"."id"
```

<!-- ZH -->
```sql
SELECT * FROM "secondDB"."user" "user", "thirdDB"."photo" "photo"
    WHERE "photo"."userId" = "user"."id"
```

<!-- EN -->
You can also specify a table path instead of the entity:

<!-- ZH -->
你也可以指定表路径来代替实体：

<!-- EN -->
```typescript
const users = await dataSource
    .createQueryBuilder()
    .select()
    .from("secondDB.user", "user")
    .addFrom("thirdDB.photo", "photo")
    .andWhere("photo.userId = user.id")
    .getMany() // userId is not a foreign key since its cross-database request
```

<!-- ZH -->
```typescript
const users = await dataSource
    .createQueryBuilder()
    .select()
    .from("secondDB.user", "user")
    .addFrom("thirdDB.photo", "photo")
    .andWhere("photo.userId = user.id")
    .getMany() // userId 不是外键，因为这是跨数据库请求
```

<!-- EN -->
This feature is supported only in mysql and mssql databases.

<!-- ZH -->
该特性仅在 mysql 和 mssql 数据库中受支持。

<!-- EN -->
## Using multiple schemas within a single data source

<!-- ZH -->
## 在单个数据源中使用多个模式

<!-- EN -->
To use multiple schemas in your applications, just set `schema` on each entity:

<!-- ZH -->
要在应用中使用多个模式，只需在每个实体上设置 `schema`：

<!-- EN -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity({ schema: "secondSchema" })
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    firstName: string

    @Column()
    lastName: string
}
```

<!-- ZH -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity({ schema: "secondSchema" })
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    firstName: string

    @Column()
    lastName: string
}
```

<!-- EN -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity({ schema: "thirdSchema" })
export class Photo {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    url: string
}
```

<!-- ZH -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity({ schema: "thirdSchema" })
export class Photo {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    url: string
}
```

<!-- EN -->
`User` entity will be created inside `secondSchema` schema and `Photo` entity inside `thirdSchema` schema. All other entities will be created in a default database defined in the data source options.

<!-- ZH -->
`User` 实体会被创建在 `secondSchema` 模式中，`Photo` 实体会被创建在 `thirdSchema` 模式中。所有其他实体都会创建在数据源选项中定义的默认数据库里。

<!-- EN -->
If you want to select data from a different schema you only need to provide an entity:

<!-- ZH -->
如果你想从另一个模式中查询数据，只需要提供一个实体：

<!-- EN -->
```typescript
const users = await dataSource
    .createQueryBuilder()
    .select()
    .from(User, "user")
    .addFrom(Photo, "photo")
    .andWhere("photo.userId = user.id")
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .createQueryBuilder()
    .select()
    .from(User, "user")
    .addFrom(Photo, "photo")
    .andWhere("photo.userId = user.id")
    .getMany()
```

<!-- EN -->
This code will produce following SQL query (depend on database type):

<!-- ZH -->
这段代码会生成如下 SQL 查询（取决于数据库类型）：

<!-- EN -->
```sql
SELECT * FROM "secondSchema"."user" "user", "thirdSchema"."photo" "photo"
    WHERE "photo"."userId" = "user"."id"
```

<!-- ZH -->
```sql
SELECT * FROM "secondSchema"."user" "user", "thirdSchema"."photo" "photo"
    WHERE "photo"."userId" = "user"."id"
```

<!-- EN -->
You can also specify a table path instead of entity:

<!-- ZH -->
你也可以指定表路径来代替实体：

<!-- EN -->
```typescript
const users = await dataSource
    .createQueryBuilder()
    .select()
    .from("secondSchema.user", "user") // in mssql you can even specify a database: secondDB.secondSchema.user
    .addFrom("thirdSchema.photo", "photo") // in mssql you can even specify a database: thirdDB.thirdSchema.photo
    .andWhere("photo.userId = user.id")
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .createQueryBuilder()
    .select()
    .from("secondSchema.user", "user") // 在 mssql 中你甚至可以指定数据库：secondDB.secondSchema.user
    .addFrom("thirdSchema.photo", "photo") // 在 mssql 中你甚至可以指定数据库：thirdDB.thirdSchema.photo
    .andWhere("photo.userId = user.id")
    .getMany()
```

<!-- EN -->
This feature is supported only in postgres and mssql databases. In mssql you can also combine schemas and databases, for example:

<!-- ZH -->
该特性仅在 postgres 和 mssql 数据库中受支持。在 mssql 中你还可以把模式和数据库组合起来，例如：

<!-- EN -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity({ database: "secondDB", schema: "public" })
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    firstName: string

    @Column()
    lastName: string
}
```

<!-- ZH -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity({ database: "secondDB", schema: "public" })
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    firstName: string

    @Column()
    lastName: string
}
```

<!-- EN -->
## Replication

<!-- ZH -->
## 复制

<!-- EN -->
You can set up read/write replication using TypeORM. Example of replication options:

<!-- ZH -->
你可以用 TypeORM 搭建读写复制。复制选项示例：

<!-- EN -->
```typescript
const datasource = new DataSource({
    type: "mysql",
    logging: true,
    replication: {
        master: {
            host: "server1",
            port: 3306,
            username: "test",
            password: "test",
            database: "test",
        },
        slaves: [
            {
                host: "server2",
                port: 3306,
                username: "test",
                password: "test",
                database: "test",
            },
            {
                host: "server3",
                port: 3306,
                username: "test",
                password: "test",
                database: "test",
            },
        ],
    },
})
```

<!-- ZH -->
```typescript
const datasource = new DataSource({
    type: "mysql",
    logging: true,
    replication: {
        master: {
            host: "server1",
            port: 3306,
            username: "test",
            password: "test",
            database: "test",
        },
        slaves: [
            {
                host: "server2",
                port: 3306,
                username: "test",
                password: "test",
                database: "test",
            },
            {
                host: "server3",
                port: 3306,
                username: "test",
                password: "test",
                database: "test",
            },
        ],
    },
})
```

<!-- EN -->
With replication slaves defined, TypeORM will start sending all possible queries to slaves by default.

<!-- ZH -->
定义了复制从库之后，TypeORM 默认会开始把所有可能的查询都发往从库。

<!-- EN -->
* all queries performed by the `find` methods or `SelectQueryBuilder` will use a random `slave` instance
* all write queries performed by `update`, `create`, `InsertQueryBuilder`, `UpdateQueryBuilder`, etc will use the `master` instance
* all raw queries performed by calling `.query()` will use the `master` instance
* all schema update operations are performed using the `master` instance

<!-- ZH -->
* 由 `find` 方法或 `SelectQueryBuilder` 执行的所有查询都会使用一个随机的 `slave` 实例
* 由 `update`、`create`、`InsertQueryBuilder`、`UpdateQueryBuilder` 等执行的所有写查询都会使用 `master` 实例
* 通过调用 `.query()` 执行的所有原生查询都会使用 `master` 实例
* 所有结构更新操作都使用 `master` 实例执行

<!-- EN -->
### Explicitly selecting query destinations

<!-- ZH -->
### 显式指定查询目标

<!-- EN -->
By default, TypeORM will send all read queries to a random read slave, and all writes to the master. This means when you first add the `replication` settings to your configuration, any existing read query runners that don't explicitly specify a replication mode will start going to a slave. This is good for scalability, but if some of those queries *must* return up to date data, then you need to explicitly pass a replication mode when you create a query runner.

<!-- ZH -->
默认情况下，TypeORM 会把所有读查询发往一个随机的只读从库，把所有写操作发往主库。这意味着当你第一次把 `replication` 配置加入项目时，任何没有显式指定复制模式的已有读查询运行器都会开始走从库。这对扩展性有好处，但如果其中某些查询*必须*返回最新数据，那你就需要在创建 query runner 时显式传入复制模式。

<!-- EN -->
If you want to explicitly use the `master` for read queries, pass an explicit `ReplicationMode` when creating your `QueryRunner`;

<!-- ZH -->
如果你想在读查询中显式使用 `master`，在创建 `QueryRunner` 时传入一个显式的 `ReplicationMode`；

<!-- EN -->
```typescript
const masterQueryRunner = dataSource.createQueryRunner("master")
try {
    const postsFromMaster = await dataSource
        .createQueryBuilder(Post, "post", masterQueryRunner) // you can either pass QueryRunner as an optional argument with query builder
        .setQueryRunner(masterQueryRunner) // or use setQueryRunner which sets or overrides query builder's QueryRunner
        .getMany()
} finally {
    await masterQueryRunner.release()
}
```

<!-- ZH -->
```typescript
const masterQueryRunner = dataSource.createQueryRunner("master")
try {
    const postsFromMaster = await dataSource
        .createQueryBuilder(Post, "post", masterQueryRunner) // 你可以把 QueryRunner 作为可选参数传给 query builder
        .setQueryRunner(masterQueryRunner) // 或者使用 setQueryRunner，它会设置或覆盖 query builder 的 QueryRunner
        .getMany()
} finally {
    await masterQueryRunner.release()
}
```

<!-- EN -->
If you want to use a slave in raw queries, pass `slave` as the replication mode when creating a query runner:

<!-- ZH -->
如果你想在原生查询中使用从库，在创建 query runner 时把 `slave` 作为复制模式传入：

<!-- EN -->
```typescript
const slaveQueryRunner = dataSource.createQueryRunner("slave")
try {
    const userFromSlave = await slaveQueryRunner.query(
        "SELECT * FROM users WHERE id = $1",
        [userId],
        slaveQueryRunner,
    )
} finally {
    return slaveQueryRunner.release()
}
```

<!-- ZH -->
```typescript
const slaveQueryRunner = dataSource.createQueryRunner("slave")
try {
    const userFromSlave = await slaveQueryRunner.query(
        "SELECT * FROM users WHERE id = $1",
        [userId],
        slaveQueryRunner,
    )
} finally {
    return slaveQueryRunner.release()
}
```

<!-- EN -->
**Note**: Manually created `QueryRunner` instances must be explicitly released on their own. If you don't release your query runners, they will keep a connection checked out of the pool, and prevent other queries from using it.

<!-- ZH -->
**注意**：手动创建的 `QueryRunner` 实例必须自行显式释放。如果你不释放 query runner，它们会一直占用从连接池中取出的连接，导致其他查询无法使用该连接。

<!-- EN -->
### Adjusting the default destination for reads

<!-- ZH -->
### 调整读操作的默认目标

<!-- EN -->
If you don't want all reads to go to a `slave` instance by default, you can change the default read query destination by passing `defaultMode: "master"` in your replication options:

<!-- ZH -->
如果你不希望所有读操作默认都发往 `slave` 实例，可以在复制选项中传入 `defaultMode: "master"` 来改变读查询的默认目标：

<!-- EN -->
```typescript
const datasource = new DataSource({
    type: "mysql",
    logging: true,
    replication: {
        // set the default destination for read queries as the master instance
        defaultMode: "master",
        master: {
            host: "server1",
            port: 3306,
            username: "test",
            password: "test",
            database: "test",
        },
        slaves: [
            {
                host: "server2",
                port: 3306,
                username: "test",
                password: "test",
                database: "test",
            },
        ],
    },
})
```

<!-- ZH -->
```typescript
const datasource = new DataSource({
    type: "mysql",
    logging: true,
    replication: {
        // 把读查询的默认目标设为主库实例
        defaultMode: "master",
        master: {
            host: "server1",
            port: 3306,
            username: "test",
            password: "test",
            database: "test",
        },
        slaves: [
            {
                host: "server2",
                port: 3306,
                username: "test",
                password: "test",
                database: "test",
            },
        ],
    },
})
```

<!-- EN -->
With this mode, no queries will go to the read slaves by default, and you'll have to opt-in to sending queries to read slaves with explicit `.createQueryRunner("slave")` calls.

<!-- ZH -->
在该模式下，默认不会有任何查询发往只读从库，你必须通过显式调用 `.createQueryRunner("slave")` 才会把查询发往只读从库。

<!-- EN -->
If you're adding replication options to an existing app for the first time, this is a good option for ensuring no behavior changes right away, and instead you can slowly adopt read replicas on a query runner by query runner basis.

<!-- ZH -->
如果你是第一次给已有应用添加复制选项，这是个不错的选项：它能确保行为不会立刻发生变化，之后你可以逐个 query runner 慢慢引入只读副本。

<!-- EN -->
### Supported drivers

<!-- ZH -->
### 受支持的驱动

<!-- EN -->
Replication is supported by the MySQL, PostgreSQL, SQL Server, Cockroach, Oracle, and Spanner connection drivers.

<!-- ZH -->
MySQL、PostgreSQL、SQL Server、Cockroach、Oracle 和 Spanner 连接驱动都支持复制。

<!-- EN -->
MySQL replication supports extra configuration options:

<!-- ZH -->
MySQL 复制支持额外的配置选项：

<!-- EN -->
```typescript
{
  replication: {
    master: {
      host: "server1",
      port: 3306,
      username: "test",
      password: "test",
      database: "test"
    },
    slaves: [{
      host: "server2",
      port: 3306,
      username: "test",
      password: "test",
      database: "test"
    }, {
      host: "server3",
      port: 3306,
      username: "test",
      password: "test",
      database: "test"
    }],

    /**
    * If true, PoolCluster will attempt to reconnect when connection fails. (Default: true)
    */
    canRetry: true,

    /**
     * If connection fails, node's errorCount increases.
     * When errorCount is greater than removeNodeErrorCount, remove a node in the PoolCluster. (Default: 5)
     */
    removeNodeErrorCount: 5,

    /**
     * If connection fails, specifies the number of milliseconds before another connection attempt will be made.
     * If set to 0, then node will be removed instead and never re-used. (Default: 0)
     */
     restoreNodeTimeout: 0,

    /**
     * Determines how slaves are selected:
     * RR: Select one alternately (Round-Robin).
     * RANDOM: Select the node by random function.
     * ORDER: Select the first node available unconditionally.
     */
    selector: "RR"
  }
}
```

<!-- ZH -->
```typescript
{
  replication: {
    master: {
      host: "server1",
      port: 3306,
      username: "test",
      password: "test",
      database: "test"
    },
    slaves: [{
      host: "server2",
      port: 3306,
      username: "test",
      password: "test",
      database: "test"
    }, {
      host: "server3",
      port: 3306,
      username: "test",
      password: "test",
      database: "test"
    }],

    /**
    * 为 true 时，连接失败时 PoolCluster 会尝试重连。（默认：true）
    */
    canRetry: true,

    /**
     * 连接失败时，节点的 errorCount 会增加。
     * 当 errorCount 大于 removeNodeErrorCount 时，从 PoolCluster 中移除该节点。（默认：5）
     */
    removeNodeErrorCount: 5,

    /**
     * 连接失败时，指定隔多少毫秒后再次尝试连接。
     * 如果设为 0，则该节点会被移除且永不复用。（默认：0）
     */
     restoreNodeTimeout: 0,

    /**
     * 决定如何选择从库：
     * RR：轮流选择一个（Round-Robin）。
     * RANDOM：通过随机函数选择节点。
     * ORDER：无条件选择第一个可用节点。
     */
    selector: "RR"
  }
}
```
