# DataSource

> 英文标题：DataSource
> 官网原文：https://typeorm.io/docs/data-source/data-source
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 18 块

---

<!-- EN -->
# DataSource

<!-- ZH -->
# DataSource

<!-- EN -->
## What is a DataSource?

<!-- ZH -->
## 什么是 DataSource？

<!-- EN -->
Your interaction with the database is only possible once you setup a `DataSource`. TypeORM's `DataSource` holds your database connection settings and establishes the initial database connection or connection pool depending on the RDBMS you use.

<!-- ZH -->
只有先配置好 `DataSource`，你才能与数据库交互。TypeORM 的 `DataSource` 持有你的数据库连接配置，并根据你所使用的 RDBMS 建立初始数据库连接或连接池。

<!-- EN -->
To establish the initial connection/connection pool, you must call the `initialize` method of your `DataSource` instance.

<!-- ZH -->
要建立初始连接 / 连接池，你必须调用 `DataSource` 实例的 `initialize` 方法。

<!-- EN -->
`initialize` must only be called once: calling it again while a previous call is still in progress, or after it has succeeded, rejects with a `CannotConnectAlreadyConnectedError`. If initialization fails, the partially established connection is cleaned up and `initialize` can safely be called again.

<!-- ZH -->
`initialize` 只能调用一次：如果在上一次调用仍在进行中时再次调用，或者在它已经成功之后再调用，都会以 `CannotConnectAlreadyConnectedError` 拒绝。如果初始化失败，已部分建立的连接会被清理掉，此后可以安全地再次调用 `initialize`。

<!-- EN -->
Disconnection (closing all connections in the pool) occurs when the `destroy` method is called.

<!-- ZH -->
断开连接（关闭池中的所有连接）发生在调用 `destroy` 方法时。

<!-- EN -->
Generally, you call the `initialize` method of the `DataSource` instance on the application bootstrap, and `destroy` it after you finished working with the database. In practice, if you are building a backend for your site and your backend server always stays running - you never `destroy` a DataSource.

<!-- ZH -->
通常，你在应用启动时调用 `DataSource` 实例的 `initialize` 方法，并在用完数据库之后 `destroy` 它。实际中，如果你在为自己的站点构建后端，并且后端服务始终常驻运行——你永远不需要 `destroy` 一个 DataSource。

<!-- EN -->
## Creating a new DataSource

<!-- ZH -->
## 创建新的 DataSource

<!-- EN -->
To create a new `DataSource` instance you must initialize its constructor by calling `new DataSource` and assigning to a global variable that you'll use across your application:

<!-- ZH -->
要创建一个新的 `DataSource` 实例，你必须通过调用 `new DataSource` 来初始化它的构造函数，并把它赋值给一个在整个应用中都会用到的全局变量：

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

const AppDataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "test",
    password: "test",
    database: "test",
})

try {
    await AppDataSource.initialize()
    console.log("Data Source has been initialized!")
} catch (error) {
    console.error("Error during Data Source initialization", error)
}
```

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

const AppDataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "test",
    password: "test",
    database: "test",
})

try {
    await AppDataSource.initialize()
    console.log("Data Source has been initialized!")
} catch (error) {
    console.error("Error during Data Source initialization", error)
}
```

<!-- EN -->
It's a good idea to make `AppDataSource` globally available by `export`-ing it since you'll use this instance across your application.

<!-- ZH -->
把 `AppDataSource` 用 `export` 导出、让它在全局可用是个好主意，因为你会在整个应用中都用到这个实例。

<!-- EN -->
`DataSource` accepts `DataSourceOptions` and those options vary depending on the database `type` you use. For different database types, there are different options you can specify.

<!-- ZH -->
`DataSource` 接受 `DataSourceOptions`，而这些选项会因你使用的数据库 `type` 而异。针对不同的数据库类型，你可以指定不同的选项。

<!-- EN -->
You can define as many data sources as you need in your application, for example:

<!-- ZH -->
你可以在应用中定义任意多个需要的数据源，例如：

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

const MysqlDataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "test",
    password: "test",
    database: "test",
    entities: [__dirname + "/entities/**/*{.js,.ts}"],
})

const PostgresDataSource = new DataSource({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "test",
    password: "test",
    database: "test",
    entities: [__dirname + "/entities/**/*{.js,.ts}"],
})
```

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

const MysqlDataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "test",
    password: "test",
    database: "test",
    entities: [__dirname + "/entities/**/*{.js,.ts}"],
})

const PostgresDataSource = new DataSource({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "test",
    password: "test",
    database: "test",
    entities: [__dirname + "/entities/**/*{.js,.ts}"],
})
```

<!-- EN -->
## How to use DataSource?

<!-- ZH -->
## 如何使用 DataSource？

<!-- EN -->
Once you set your `DataSource`, you can use it anywhere in your app, for example:

<!-- ZH -->
配置好 `DataSource` 之后，你就可以在应用的任何地方使用它，例如：

<!-- EN -->
```typescript
import { AppDataSource } from "./app-data-source"
import { User } from "../entity/User"

export class UserController {
    @Get("/users")
    getAll() {
        return AppDataSource.manager.find(User)
    }
}
```

<!-- ZH -->
```
import { AppDataSource } from "./app-data-source"
import { User } from "../entity/User"

export class UserController {
    @Get("/users")
    getAll() {
        return AppDataSource.manager.find(User)
    }
}
```

<!-- EN -->
Using the `DataSource` instance you can execute database operations with your entities, particularly using `.manager` and `.getRepository()` properties. For more information about them see [Entity Manager](https://typeorm.io/docs/working-with-entity-manager/working-with-entity-manager) and [Repository](https://typeorm.io/docs/working-with-entity-manager/working-with-repository) documentation.

<!-- ZH -->
借助 `DataSource` 实例，你可以对实体执行数据库操作，尤其是通过 `.manager` 和 `.getRepository()` 这两个属性。关于它们的更多信息，请参阅 [Entity Manager](https://typeorm.io/docs/working-with-entity-manager/working-with-entity-manager) 和 [Repository](https://typeorm.io/docs/working-with-entity-manager/working-with-repository) 文档。
