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;
改编自这个答案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句