0

I want to create new table countries with default rows. I am using sequelize with pg and I am wondering if there is a way to check if a table already exists if not execute a sql file. Also, I made a sequelize model country, and maybe there is a hook to bulk all data after creating a table?

Vitoo
  • 21
  • 5

1 Answers1

1

You can check if a table exists by executing a query from information_schema, see this answer.
To bulk load data use the same migration file and place all data as a script in sql-file, read it and execute it there:

'use strict'

const fs = require('fs')
const path = require('path')

const sqlUp = fs.readFileSync(path.join(__dirname, '../scripts/bulk-insert-data.sql'), { encoding: 'utf8' })

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.sequelize.transaction(async transaction => {
      await queryInterface.createTable('table', {
       // here are column definitions
      }, { transaction })

      await queryInterface.sequelize.query(sqlUp, { type: queryInterface.sequelize.QueryTypes.RAW, transaction })
    })
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable('table')
  }
}

Anatoly
  • 20,799
  • 3
  • 28
  • 42