How to programmatically run sequelize migrations

橙三吉。 提交于 2020-12-29 05:47:22

问题


The documentation for sequelize seems out of date as they no longer support running migrations from sequelize itself, but instead relies on sequelize-cli. Is there an example of how to use sequeliz-cli programmatically to run the latest migrations? All the documentation seems to be focused on using the client in a shell.

db.js seems to have the function db:migrate that perhaps I can include.

https://github.com/sequelize/cli/blob/master/lib/tasks/db.js


回答1:


I dug into the code for the sequelize db:migrate command, and there's enough going on there that, IMHO, the simplest/best approach is to just run the command in a child process. Here's the code I used for this (as an await'ed Promise):

const {exec} = require('child_process');

await new Promise((resolve, reject) => {
  const migrate = exec(
    'sequelize db:migrate',
    {env: process.env},
    err => (err ? reject(err): resolve())
  );

  // Forward stdout+stderr to this process
  migrate.stdout.pipe(process.stdout);
  migrate.stderr.pipe(process.stderr);
});



回答2:


This is what I did. It is not yet extensively tested, and probably can be optimized further:

const Sequelize = require('sequelize');
const db = new Sequelize('main', 'test', 'test', {
dialect: 'sqlite',
// SQLite only
storage: 'db.db'
});

async function checkForMigrations() {
let migrations = fs.readdirSync(__dirname + '/../migrations');
let completedMigrations = await db.query("SELECT * FROM `SequelizeMeta`", {type: Sequelize.QueryTypes.SELECT});
for (let name in completedMigrations) {
    if (completedMigrations.hasOwnProperty(name)) {
        let index = migrations.indexOf(completedMigrations[name].name);
        if (index !== -1) {
            migrations.splice(index, 1);
        }
    }
}

for(let i = 0, c = migrations.length; i < c; i++){
   let migration = require(__dirname + '/../migrations/' + migrations[i]);
   migration.up(db.queryInterface, Sequelize);
   await db.query("INSERT INTO `SequelizeMeta` VALUES(:name)", {type: Sequelize.QueryTypes.INSERT, replacements: {name: migrations[i]}})
}
}


来源:https://stackoverflow.com/questions/30848530/how-to-programmatically-run-sequelize-migrations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!