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({....});
}
那么,在对表进行数据库操作之前,我们如何首先添加对表存在性的检查呢?
如果可以使用原始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;
根据这个答案改编。