# DataSource API

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

---

<!-- EN -->
# DataSource API

<!-- ZH -->
# DataSource API

<!-- EN -->
* `options` - Options used to create this dataSource. Learn more about [Data Source Options](https://typeorm.io/docs/data-source/data-source-options).

<!-- ZH -->
* `options` - 创建该 dataSource 所使用的选项。进一步了解[数据源选项](https://typeorm.io/docs/data-source/data-source-options)。

<!-- EN -->
```typescript
const dataSourceOptions: DataSourceOptions = dataSource.options
```

<!-- ZH -->
```typescript
const dataSourceOptions: DataSourceOptions = dataSource.options
```

<!-- EN -->
* `isInitialized` - Indicates if the `DataSource` was initialized and the connection / connection pool with the database was established or not.

<!-- ZH -->
* `isInitialized` - 表示 `DataSource` 是否已初始化，以及与数据库的连接 / 连接池是否已建立。

<!-- EN -->
```typescript
const isInitialized: boolean = dataSource.isInitialized
```

<!-- ZH -->
```typescript
const isInitialized: boolean = dataSource.isInitialized
```

<!-- EN -->
* `driver` - Underlying database driver used in this dataSource.

<!-- ZH -->
* `driver` - 该 dataSource 所使用的底层数据库驱动。

<!-- EN -->
```typescript
const driver: Driver = dataSource.driver
```

<!-- ZH -->
```typescript
const driver: Driver = dataSource.driver
```

<!-- EN -->
* `manager` - `EntityManager` used to work with entities. Learn more about [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).

<!-- ZH -->
* `manager` - 用于操作实体的 `EntityManager`。进一步了解 [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)。

<!-- EN -->
```typescript
const manager: EntityManager = dataSource.manager
// you can call manager methods, for example find:
const users = await manager.find()
```

<!-- ZH -->
```typescript
const manager: EntityManager = dataSource.manager
// 你可以调用 manager 的方法，例如 find：
const users = await manager.find()
```

<!-- EN -->
* `mongoManager` - `MongoEntityManager` used to work with entities for mongodb data source. For more information about MongoEntityManager see [MongoDB](https://typeorm.io/docs/drivers/mongodb) documentation.

<!-- ZH -->
* `mongoManager` - 用于操作 mongodb 数据源中实体的 `MongoEntityManager`。关于 MongoEntityManager 的更多信息，请参阅 [MongoDB](https://typeorm.io/docs/drivers/mongodb) 文档。

<!-- EN -->
```typescript
const manager: MongoEntityManager = dataSource.mongoManager
// you can call manager or mongodb-manager specific methods, for example find:
const users = await manager.find()
```

<!-- ZH -->
```typescript
const manager: MongoEntityManager = dataSource.mongoManager
// 你可以调用 manager 或 mongodb-manager 特有的方法，例如 find：
const users = await manager.find()
```

<!-- EN -->
* `initialize` - Initializes data source and opens connection pool to the database.

<!-- ZH -->
* `initialize` - 初始化数据源并打开到数据库的连接池。

<!-- EN -->
```typescript
await dataSource.initialize()
```

<!-- ZH -->
```typescript
await dataSource.initialize()
```

<!-- EN -->
* `destroy` - Destroys the DataSource and closes all database connections. Usually, you call this method when your application is shutting down.

<!-- ZH -->
* `destroy` - 销毁 DataSource 并关闭所有数据库连接。通常在应用关闭时调用该方法。

<!-- EN -->
```typescript
await dataSource.destroy()
```

<!-- ZH -->
```typescript
await dataSource.destroy()
```

<!-- EN -->
* `synchronize` - Synchronizes database schema. When `synchronize: true` is set in data source options it calls this method. Usually, you call this method when your application is starting.

<!-- ZH -->
* `synchronize` - 同步数据库结构。当数据源选项中设置了 `synchronize: true` 时，它调用的就是这个方法。通常在应用启动时调用该方法。

<!-- EN -->
```typescript
await dataSource.synchronize()
```

<!-- ZH -->
```typescript
await dataSource.synchronize()
```

<!-- EN -->
* `dropDatabase` - Drops the database and all its data. Be careful with this method on production since this method will erase all your database tables and their data. Can be used only after connection to the database is established.

<!-- ZH -->
* `dropDatabase` - 删除数据库及其全部数据。在生产环境中请谨慎使用该方法，因为它会抹掉你所有的数据库表及其数据。只能在数据库连接建立之后使用。

<!-- EN -->
```typescript
await dataSource.dropDatabase()
```

<!-- ZH -->
```typescript
await dataSource.dropDatabase()
```

<!-- EN -->
* `runMigrations` - Runs all pending migrations.

<!-- ZH -->
* `runMigrations` - 运行所有待执行的迁移。

<!-- EN -->
```typescript
await dataSource.runMigrations()
```

<!-- ZH -->
```typescript
await dataSource.runMigrations()
```

<!-- EN -->
* `undoLastMigration` - Reverts last executed migration.

<!-- ZH -->
* `undoLastMigration` - 回滚最近一次执行的迁移。

<!-- EN -->
```typescript
await dataSource.undoLastMigration()
```

<!-- ZH -->
```typescript
await dataSource.undoLastMigration()
```

<!-- EN -->
* `hasMetadata` - Checks if metadata for a given entity is registered.

<!-- ZH -->
* `hasMetadata` - 检查给定实体的元数据是否已注册。

<!-- EN -->
```typescript
if (dataSource.hasMetadata(User))
    const userMetadata = dataSource.getMetadata(User)
```

<!-- ZH -->
```typescript
if (dataSource.hasMetadata(User))
    const userMetadata = dataSource.getMetadata(User)
```

<!-- EN -->
* `getMetadata` - Gets `EntityMetadata` of the given entity. You can also specify a table name and if entity metadata with such table name is found it will be returned.

<!-- ZH -->
* `getMetadata` - 获取给定实体的 `EntityMetadata`。你也可以指定表名，如果找到了该表名对应的实体元数据，就会返回它。

<!-- EN -->
```typescript
const userMetadata = dataSource.getMetadata(User)
// now you can get any information about User entity
```

<!-- ZH -->
```typescript
const userMetadata = dataSource.getMetadata(User)
// 现在你可以获取关于 User 实体的任何信息
```

<!-- EN -->
* `getRepository` - Gets `Repository` of the given entity. You can also specify a table name and if repository for given table is found it will be returned. Learn more about [Repositories](https://typeorm.io/docs/working-with-entity-manager/working-with-repository).

<!-- ZH -->
* `getRepository` - 获取给定实体的 `Repository`。你也可以指定表名，如果找到了该表对应的 repository，就会返回它。进一步了解 [Repository](https://typeorm.io/docs/working-with-entity-manager/working-with-repository)。

<!-- EN -->
```typescript
const repository = dataSource.getRepository(User)
// now you can call repository methods, for example find:
const users = await repository.find()
```

<!-- ZH -->
```typescript
const repository = dataSource.getRepository(User)
// 现在你可以调用 repository 的方法，例如 find：
const users = await repository.find()
```

<!-- EN -->
* `getTreeRepository` - Gets `TreeRepository` of the given entity. You can also specify a table name and if repository for given table is found it will be returned. Learn more about [Repositories](https://typeorm.io/docs/working-with-entity-manager/working-with-repository).

<!-- ZH -->
* `getTreeRepository` - 获取给定实体的 `TreeRepository`。你也可以指定表名，如果找到了该表对应的 repository，就会返回它。进一步了解 [Repository](https://typeorm.io/docs/working-with-entity-manager/working-with-repository)。

<!-- EN -->
```typescript
const repository = dataSource.getTreeRepository(Category)
// now you can call tree repository methods, for example findTrees:
const categories = await repository.findTrees()
```

<!-- ZH -->
```typescript
const repository = dataSource.getTreeRepository(Category)
// 现在你可以调用 tree repository 的方法，例如 findTrees：
const categories = await repository.findTrees()
```

<!-- EN -->
* `getMongoRepository` - Gets `MongoRepository` of the given entity. This repository is used for entities in MongoDB dataSource. Learn more about [MongoDB support](https://typeorm.io/docs/drivers/mongodb).

<!-- ZH -->
* `getMongoRepository` - 获取给定实体的 `MongoRepository`。该 repository 用于 MongoDB dataSource 中的实体。进一步了解 [MongoDB 支持](https://typeorm.io/docs/drivers/mongodb)。

<!-- EN -->
```typescript
const repository = dataSource.getMongoRepository(User)
// now you can call mongodb-specific repository methods, for example createEntityCursor:
const categoryCursor = repository.createEntityCursor()
const category1 = await categoryCursor.next()
const category2 = await categoryCursor.next()
```

<!-- ZH -->
```typescript
const repository = dataSource.getMongoRepository(User)
// 现在你可以调用 mongodb 特有的 repository 方法，例如 createEntityCursor：
const categoryCursor = repository.createEntityCursor()
const category1 = await categoryCursor.next()
const category2 = await categoryCursor.next()
```

<!-- EN -->
* `transaction` - Provides a single transaction where multiple database requests will be executed in a single database transaction. Learn more about [Transactions](https://typeorm.io/docs/transactions).

<!-- ZH -->
* `transaction` - 提供一个事务，在其中多个数据库请求会在同一个数据库事务中执行。进一步了解[事务](https://typeorm.io/docs/transactions)。

<!-- EN -->
```typescript
await dataSource.transaction(async (manager) => {
    // NOTE: you must perform all database operations using given manager instance
    // its a special instance of EntityManager working with this transaction
    // and don't forget to await things here
})
```

<!-- ZH -->
```typescript
await dataSource.transaction(async (manager) => {
    // 注意：你必须使用给定的 manager 实例执行所有数据库操作
    // 它是一个与该事务协同工作的特殊 EntityManager 实例
    // 并且别忘了在这里 await 各个操作
})
```

<!-- EN -->
* `query` - Executes a raw SQL query.

<!-- ZH -->
* `query` - 执行一条原生 SQL 查询。

<!-- EN -->
```typescript
const rawData = await dataSource.query(`SELECT * FROM USERS`)

// You can also use parameters to avoid SQL injection
// The syntax differs between the drivers

// aurora-mysql, better-sqlite3, capacitor, cordova,
// expo, mariadb, mysql, nativescript, react-native,
// sap, sqlite, sqljs
const rawData = await dataSource.query(
    "SELECT * FROM USERS WHERE name = ? and age = ?",
    ["John", 24],
)

// mysql2 additionally supports named parameters
// when extra.namedPlaceholders is true
const rawData = await dataSource.query(
    "SELECT * FROM USERS WHERE name = :name and age = :age",
    { name: "John", age: 24 },
)

// aurora-postgres, cockroachdb, postgres
const rawData = await dataSource.query(
    "SELECT * FROM USERS WHERE name = $1 and age = $2",
    ["John", 24],
)

// oracle
const rawData = await dataSource.query(
    "SELECT * FROM USERS WHERE name = :1 and age = :2",
    ["John", 24],
)

// spanner
const rawData = await dataSource.query(
    "SELECT * FROM USERS WHERE name = @param0 and age = @param1",
    ["John", 24],
)

// mssql
const rawData = await dataSource.query(
    "SELECT * FROM USERS WHERE name = @0 and age = @1",
    ["John", 24],
)
```

<!-- ZH -->
```typescript
const rawData = await dataSource.query(`SELECT * FROM USERS`)

// 你也可以使用参数来避免 SQL 注入
// 不同驱动的语法有所不同

// aurora-mysql, better-sqlite3, capacitor, cordova,
// expo, mariadb, mysql, nativescript, react-native,
// sap, sqlite, sqljs
const rawData = await dataSource.query(
    "SELECT * FROM USERS WHERE name = ? and age = ?",
    ["John", 24],
)

// 当 extra.namedPlaceholders 为 true 时
// mysql2 还额外支持具名参数
const rawData = await dataSource.query(
    "SELECT * FROM USERS WHERE name = :name and age = :age",
    { name: "John", age: 24 },
)

// aurora-postgres, cockroachdb, postgres
const rawData = await dataSource.query(
    "SELECT * FROM USERS WHERE name = $1 and age = $2",
    ["John", 24],
)

// oracle
const rawData = await dataSource.query(
    "SELECT * FROM USERS WHERE name = :1 and age = :2",
    ["John", 24],
)

// spanner
const rawData = await dataSource.query(
    "SELECT * FROM USERS WHERE name = @param0 and age = @param1",
    ["John", 24],
)

// mssql
const rawData = await dataSource.query(
    "SELECT * FROM USERS WHERE name = @0 and age = @1",
    ["John", 24],
)
```

<!-- EN -->
* `sql` - Executes a raw SQL query using template literals.

<!-- ZH -->
* `sql` - 使用模板字符串执行一条原生 SQL 查询。

<!-- EN -->
```typescript
const rawData =
    await dataSource.sql`SELECT * FROM USERS WHERE name = ${"John"} and age = ${24}`
```

<!-- ZH -->
```typescript
const rawData =
    await dataSource.sql`SELECT * FROM USERS WHERE name = ${"John"} and age = ${24}`
```

<!-- EN -->
Learn more about using the [SQL Tag syntax](https://typeorm.io/docs/guides/sql-tag).

<!-- ZH -->
进一步了解 [SQL 标签语法](https://typeorm.io/docs/guides/sql-tag)的用法。

<!-- EN -->
* `createQueryBuilder` - Creates a query builder, which can be used to build queries. Learn more about [QueryBuilder](https://typeorm.io/docs/query-builder/select-query-builder).

<!-- ZH -->
* `createQueryBuilder` - 创建一个 query builder，可用于构建查询。进一步了解 [QueryBuilder](https://typeorm.io/docs/query-builder/select-query-builder)。

<!-- EN -->
```typescript
const users = await dataSource
    .createQueryBuilder()
    .select()
    .from(User, "user")
    .where("user.name = :name", { name: "John" })
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .createQueryBuilder()
    .select()
    .from(User, "user")
    .where("user.name = :name", { name: "John" })
    .getMany()
```

<!-- EN -->
* `createQueryRunner` - Creates a query runner used to manage and work with a single real database dataSource. Learn more about [QueryRunner](https://typeorm.io/docs/query-runner).

<!-- ZH -->
* `createQueryRunner` - 创建一个 query runner，用于管理和操作单个真实的数据库 dataSource。进一步了解 [QueryRunner](https://typeorm.io/docs/query-runner)。

<!-- EN -->
```typescript
const queryRunner = dataSource.createQueryRunner()

// you can use its methods only after you call connect
// which performs real database connection
await queryRunner.connect()

// .. now you can work with query runner and call its methods

// very important - don't forget to release query runner once you finished working with it
await queryRunner.release()
```

<!-- ZH -->
```typescript
const queryRunner = dataSource.createQueryRunner()

// 只有在调用 connect 之后你才能使用它的方法
// connect 会建立真实的数据库连接
await queryRunner.connect()

// .. 现在你可以操作 query runner 并调用它的方法了

// 非常重要——用完之后别忘了释放 query runner
await queryRunner.release()
```
