I have a set of Sequelize models. I want to use migrations, not DB Sync.
Sequelize CLI seems to be able to do this, according to this article: \"When you use the CLI
While it doesn't auto generate, one way to generate new migrations on a change to a model is: (assuming that you're using the stock sequelize-cli file structure where migrations, and models are on the same level)
(Same as Manuel Bieh's suggestion, but using a require instead of an import) In your migration file (if you don't have one, you can generate one by doing "sequelize migration:create
") have the following code:
'use strict';
var models = require("../models/index.js")
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable(models.User.tableName,
models.User.attributes);
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('Users');
}
};
Make a change to the User model.
sequelize db:migrate:undo:all
sequelize db:migrate
If you want to create model along with migration use this command:-
sequelize model:create --name regions --attributes name:string,status:boolean --underscored
--underscored it is used to create column having underscore like:- created_at,updated_at or any other column having underscore and support user defined columns having underscore.
If you don't want to recreate your model from scratch, you can manually generate a migration file using the following CLI command:
sequelize migration:generate --name [name_of_your_migration]
This will generate a blank skeleton migration file. While it doesn't copy your model structure over to the file, I do find it easier and cleaner than regenerating everything. Note: make sure to run the command from the containing directory of your migrations directory; otherwise the CLI will generate a new migration dir for you
I created a small working "migration file generator". It creates files which are working perfectly fine using sequelize db:migrate
- even with foreign keys!
You can find it here: https://gist.github.com/manuelbieh/ae3b028286db10770c81
I tested it in an application with 12 different models covering:
STRING, TEXT, ENUM, INTEGER, BOOLEAN, FLOAT as DataTypes
Foreign key constraints (even reciprocal (user belongsTo team, team belongsTo user as owner))
Indexes with name
, method
and unique
properties