在 typeorm 中,我们如何检查 table 是否已经存在?
how can we check whether a table already exists or not, in typeorm?
postgresql, typeorm
在开始对 table
进行数据库操作之前,我们如何检查 table
是否已经存在于数据库中?
目前我的代码是这样的,我检查一个项目是否存在于数据库中。但这种方法的问题在于,如果它是全新部署,并且 tables
不存在,则会抛出 exception
。
const found = await this.userRepository.findOne(undefined); //<<< throws exception if tables not already created
if (found === undefined) {
const item: Items = this.userRepository.create({....});
}
那么我们如何才能在对 table 进行数据库操作之前先检查它是否存在?
如果您可以为此使用原始 SQL 查询,您可以从用户存储库中获取实体管理器和 运行 查询以检查信息模式。只需将以下代码段替换为您的 SCHEMA_NAME 和 TABLE_NAME.
const tableExists = (
await this.userRepository.manager.query(
`SELECT exists (
SELECT FROM information_schema.tables
WHERE table_schema = 'SCHEMA_NAME'
AND table_name = 'TABLE_NAME'
)`,
)
)[0].exists;
改编自this answer。
postgresql, typeorm
在开始对 table
进行数据库操作之前,我们如何检查 table
是否已经存在于数据库中?
目前我的代码是这样的,我检查一个项目是否存在于数据库中。但这种方法的问题在于,如果它是全新部署,并且 tables
不存在,则会抛出 exception
。
const found = await this.userRepository.findOne(undefined); //<<< throws exception if tables not already created
if (found === undefined) {
const item: Items = this.userRepository.create({....});
}
那么我们如何才能在对 table 进行数据库操作之前先检查它是否存在?
如果您可以为此使用原始 SQL 查询,您可以从用户存储库中获取实体管理器和 运行 查询以检查信息模式。只需将以下代码段替换为您的 SCHEMA_NAME 和 TABLE_NAME.
const tableExists = (
await this.userRepository.manager.query(
`SELECT exists (
SELECT FROM information_schema.tables
WHERE table_schema = 'SCHEMA_NAME'
AND table_name = 'TABLE_NAME'
)`,
)
)[0].exists;
改编自this answer。