Home > OS >  how can we check whether a table already exists or not, in typeorm?
how can we check whether a table already exists or not, in typeorm?

Time:03-31

postgresql, typeorm how can we check whether a table already exists in a database before starting database operations on that table?

currently my code is like this, i check whether an item is present in database. But the problem with this approach is that, if its a fresh deployment, and if the tables are not present, then an exception is thrown.

const found = await this.userRepository.findOne(undefined);   //<<< throws exception if tables not already created

if (found === undefined) {
    const item: Items = this.userRepository.create({....});
}

so how can we add a check for a table's existance first, before doing database operations on it?

CodePudding user response:

If you can use raw SQL queries for this, you can get the Entity Manager from the User Repository and run a query to check the information schema. Just replace the following snippet with your SCHEMA_NAME and 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;

Adapted from this answer.

  • Related