DataSource API
options- 创建该 dataSource 所使用的选项。进一步了解数据源选项。
const dataSourceOptions: DataSourceOptions = dataSource.optionsisInitialized- 表示DataSource是否已初始化,以及与数据库的连接 / 连接池是否已建立。
const isInitialized: boolean = dataSource.isInitializeddriver- 该 dataSource 所使用的底层数据库驱动。
const driver: Driver = dataSource.drivermanager- 用于操作实体的EntityManager。进一步了解 Entity Manager 和 Repository。
const manager: EntityManager = dataSource.manager
// 你可以调用 manager 的方法,例如 find:
const users = await manager.find()mongoManager- 用于操作 mongodb 数据源中实体的MongoEntityManager。关于 MongoEntityManager 的更多信息,请参阅 MongoDB 文档。
const manager: MongoEntityManager = dataSource.mongoManager
// 你可以调用 manager 或 mongodb-manager 特有的方法,例如 find:
const users = await manager.find()initialize- 初始化数据源并打开到数据库的连接池。
await dataSource.initialize()destroy- 销毁 DataSource 并关闭所有数据库连接。通常在应用关闭时调用该方法。
await dataSource.destroy()synchronize- 同步数据库结构。当数据源选项中设置了synchronize: true时,它调用的就是这个方法。通常在应用启动时调用该方法。
await dataSource.synchronize()dropDatabase- 删除数据库及其全部数据。在生产环境中请谨慎使用该方法,因为它会抹掉你所有的数据库表及其数据。只能在数据库连接建立之后使用。
await dataSource.dropDatabase()runMigrations- 运行所有待执行的迁移。
await dataSource.runMigrations()undoLastMigration- 回滚最近一次执行的迁移。
await dataSource.undoLastMigration()hasMetadata- 检查给定实体的元数据是否已注册。
if (dataSource.hasMetadata(User))
const userMetadata = dataSource.getMetadata(User)getMetadata- 获取给定实体的EntityMetadata。你也可以指定表名,如果找到了该表名对应的实体元数据,就会返回它。
const userMetadata = dataSource.getMetadata(User)
// 现在你可以获取关于 User 实体的任何信息getRepository- 获取给定实体的Repository。你也可以指定表名,如果找到了该表对应的 repository,就会返回它。进一步了解 Repository。
const repository = dataSource.getRepository(User)
// 现在你可以调用 repository 的方法,例如 find:
const users = await repository.find()getTreeRepository- 获取给定实体的TreeRepository。你也可以指定表名,如果找到了该表对应的 repository,就会返回它。进一步了解 Repository。
const repository = dataSource.getTreeRepository(Category)
// 现在你可以调用 tree repository 的方法,例如 findTrees:
const categories = await repository.findTrees()getMongoRepository- 获取给定实体的MongoRepository。该 repository 用于 MongoDB dataSource 中的实体。进一步了解 MongoDB 支持。
const repository = dataSource.getMongoRepository(User)
// 现在你可以调用 mongodb 特有的 repository 方法,例如 createEntityCursor:
const categoryCursor = repository.createEntityCursor()
const category1 = await categoryCursor.next()
const category2 = await categoryCursor.next()transaction- 提供一个事务,在其中多个数据库请求会在同一个数据库事务中执行。进一步了解事务。
await dataSource.transaction(async (manager) => {
// 注意:你必须使用给定的 manager 实例执行所有数据库操作
// 它是一个与该事务协同工作的特殊 EntityManager 实例
// 并且别忘了在这里 await 各个操作
})query- 执行一条原生 SQL 查询。
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],
)sql- 使用模板字符串执行一条原生 SQL 查询。
const rawData =
await dataSource.sql`SELECT * FROM USERS WHERE name = ${"John"} and age = ${24}`进一步了解 SQL 标签语法的用法。
createQueryBuilder- 创建一个 query builder,可用于构建查询。进一步了解 QueryBuilder。
const users = await dataSource
.createQueryBuilder()
.select()
.from(User, "user")
.where("user.name = :name", { name: "John" })
.getMany()createQueryRunner- 创建一个 query runner,用于管理和操作单个真实的数据库 dataSource。进一步了解 QueryRunner。
const queryRunner = dataSource.createQueryRunner()
// 只有在调用 connect 之后你才能使用它的方法
// connect 会建立真实的数据库连接
await queryRunner.connect()
// .. 现在你可以操作 query runner 并调用它的方法了
// 非常重要——用完之后别忘了释放 query runner
await queryRunner.release()options- Options used to create this dataSource. Learn more about Data Source Options.
const dataSourceOptions: DataSourceOptions = dataSource.optionsisInitialized- Indicates if theDataSourcewas initialized and the connection / connection pool with the database was established or not.
const isInitialized: boolean = dataSource.isInitializeddriver- Underlying database driver used in this dataSource.
const driver: Driver = dataSource.drivermanager-EntityManagerused to work with entities. Learn more about Entity Manager and Repository.
const manager: EntityManager = dataSource.manager
// you can call manager methods, for example find:
const users = await manager.find()mongoManager-MongoEntityManagerused to work with entities for mongodb data source. For more information about MongoEntityManager see MongoDB documentation.
const manager: MongoEntityManager = dataSource.mongoManager
// you can call manager or mongodb-manager specific methods, for example find:
const users = await manager.find()initialize- Initializes data source and opens connection pool to the database.
await dataSource.initialize()destroy- Destroys the DataSource and closes all database connections. Usually, you call this method when your application is shutting down.
await dataSource.destroy()synchronize- Synchronizes database schema. Whensynchronize: trueis set in data source options it calls this method. Usually, you call this method when your application is starting.
await dataSource.synchronize()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.
await dataSource.dropDatabase()runMigrations- Runs all pending migrations.
await dataSource.runMigrations()undoLastMigration- Reverts last executed migration.
await dataSource.undoLastMigration()hasMetadata- Checks if metadata for a given entity is registered.
if (dataSource.hasMetadata(User))
const userMetadata = dataSource.getMetadata(User)getMetadata- GetsEntityMetadataof the given entity. You can also specify a table name and if entity metadata with such table name is found it will be returned.
const userMetadata = dataSource.getMetadata(User)
// now you can get any information about User entitygetRepository- GetsRepositoryof 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.
const repository = dataSource.getRepository(User)
// now you can call repository methods, for example find:
const users = await repository.find()getTreeRepository- GetsTreeRepositoryof 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.
const repository = dataSource.getTreeRepository(Category)
// now you can call tree repository methods, for example findTrees:
const categories = await repository.findTrees()getMongoRepository- GetsMongoRepositoryof the given entity. This repository is used for entities in MongoDB dataSource. Learn more about MongoDB support.
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()transaction- Provides a single transaction where multiple database requests will be executed in a single database transaction. Learn more about Transactions.
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
})query- Executes a raw SQL query.
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],
)sql- Executes a raw SQL query using template literals.
const rawData =
await dataSource.sql`SELECT * FROM USERS WHERE name = ${"John"} and age = ${24}`Learn more about using the SQL Tag syntax.
createQueryBuilder- Creates a query builder, which can be used to build queries. Learn more about QueryBuilder.
const users = await dataSource
.createQueryBuilder()
.select()
.from(User, "user")
.where("user.name = :name", { name: "John" })
.getMany()createQueryRunner- Creates a query runner used to manage and work with a single real database dataSource. Learn more about QueryRunner.
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()