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?

0

1 Answer 1

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')
  }
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.