Running migrations (sequelize), on Azure database

78 views Asked by At

I need to run the migrations to create the tables in my database, currently my database is on an azure MySQL server, how do I run the migrations from my local host?

Currently when I run the command it returns this result

npx sequelize-cli db:migrate

Sequelize CLI [Node: 18.18.0, CLI: 6.6.2, ORM: 6.35.2]

Loaded configuration file "config\config.json".
Using environment "development".
No migrations were executed, database schema was already up to date.
1

There are 1 answers

0
Sampath On

Steps for Sequelize migrations targeting an Azure MySQL database

  • Install the Sequelize CLI using npm with the command npm install --save-dev sequelize-cli.
  • The npx sequelize-cli init command initializes a Sequelize project, creating folders like config, models, migrations, and seeders.
  • Database connection details are specified in the config/config.json file.
  • To generate models and migrations with the npx sequelize-cli model:generate command.
  • The .sequelizerc file is used to specify project configurations, allowing customization of paths for models, migrations, seeders, and the configuration file.

With Mysql: Create .sequelizerc File:

// .sequelizerc
const path = require('path');

module.exports = {
  'config': path.resolve('config', 'config.js'),
  'models-path': path.resolve('db', 'models'),
  'migrations-path': path.resolve('db', 'migrations'),
  'seeders-path': path.resolve('db', 'seeders')
};

Create config/config.js File:

// config/config.js
require('dotenv').config();

module.exports = {
  development: {
    username: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_DATABASE,
    host: process.env.DB_HOST,
    port: process.env.DB_PORT || 3306,
    dialect: 'mysql'
  },
  production: {
    // Add your production database configuration here
  }
};


Create Sequelize Model and Migration:

Used to generate the model in db/models/user.js and a migration file in db/migrations/.

npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string

enter image description here

Run Migration:

The npx sequelize-cli db:migrate command is used to apply migrations and create or update the corresponding database tables.

npx sequelize-cli db:migrate

enter image description here

With Azure my SQL:

// config/config.js
require('dotenv').config();
const fs = require('fs');

module.exports = {
  development: {
    username: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_DATABASE,
    host: process.env.DB_HOST,
    port: process.env.DB_PORT || 3306,
    dialect: 'mysql',
    dialectOptions: {
      ssl: {
        ca: fs.readFileSync('{path-to-your-ca-cert-file}'),  // Provide the path to your CA cert file
      }
    }
  },
  production: {
    // Add your production database configuration here
  }
};


enter image description here