umzug icon indicating copy to clipboard operation
umzug copied to clipboard

Sequelize migration example

Open heijmerikx opened this issue 11 years ago • 9 comments

Hi there!

I'm trying to wrap my head around umzug and can't seem to figure out how to actually run a Sequalize migration in the proposed format given here: https://github.com/sequelize/umzug#format

I'm probably in error having read the Sequalize migration documentation, because I'm missing the passed migration object which is referenced in those docs.

An example on how to execute a Sequalize migration in the proposed format is very welcome!

Thanks in advanced for the effort.

Regards,

Rutger

heijmerikx avatar Feb 09 '15 13:02 heijmerikx

Hi Rutger,

the migration object can be found here: https://sequelize.readthedocs.org/en/latest/docs/migrations/#functions

Does that help?

sdepold avatar Feb 10 '15 07:02 sdepold

Hi Sascha,

Unfortunately not. How do I access the migration object from this example?

'use strict';

var Bluebird = require('bluebird');

module.exports = {
    up: function () {
        return new Bluebird(function (resolve, reject) {
            // Describe how to achieve the task.
            // Call resolve/reject at some point.
            migration.addColumn('Users', 'active', DataTypes.STRING);
            resolve();
        });
    },

    down: function () {
        return new Bluebird(function (resolve, reject) {
            // Describe how to revert the task.
            // Call resolve/reject at some point.
            migration.removeColumn('User', 'active');
            resolve();
        });
    }
};

In the documentation it can be accessed by passing it as a function parameter, but this doesn't apply now. It's probably a newbie question too.

heijmerikx avatar Feb 10 '15 07:02 heijmerikx

Was hitting the same wall here, took me some time and digging through the old migrator's source code but this seems to to the job.

From what I can tell migration was just a fancy proxy for the queryInterface of the sequelize instance:

var umzug = new Umzug({

    storage: 'sequelize',

    storageOptions: {
        sequelize: sequlizeInstance,
    },

    migrations: {
        params: [sequlizeInstance.getQueryInterface(), sequlizeInstance.constructor, function() {
            throw new Error('Migration tried to use old style "done" callback. Please upgrade to "umzug" and return a promise instead.');
        }],
        path: './migrations',
        pattern: /\.js$/
    }

});

 umzug.up().then(function()  {
     console.log('Migration complete!');
 });

The existing migrations can the be used with minimal changes, just remove the done callback stuff and return the promise:

"use strict";

module.exports = {

    up: function(migration, DataTypes) {

        return migration.createTable('Sessions', {

            sid: {
                type: DataTypes.STRING,
                allowNull: false
            },

            data: {
                type: DataTypes.STRING,
                allowNull: false
            },

            createdAt: {
                type: DataTypes.DATE
            },

            updatedAt: {
                type: DataTypes.DATE
            }

        }).then(function() {
            return migration.addIndex('Sessions', ['sid']);

        });

    },

    down: function(migration, DataTypes) {
        return migration.dropTable('Sessions');
    }

};

BonsaiDen avatar Feb 17 '15 11:02 BonsaiDen

Thanks a lot for your reply! Very helpful, got it working.

heijmerikx avatar Feb 17 '15 12:02 heijmerikx

One more thing, if you have existing data in your SequelizeMeta table thing won't play out very well once you want to run migrations since the table formats (id, from, to vs. name) differ drastically.

I had to write a rather messy piece of bootstrapping code in order to get this working.

@sdepold There's definitely the need for a migration guide from the old Sequelize Migration format to Umzug, otherwise I see a lot of people getting frustrated by the experience, especially when it comes to upgrading production environments (I spend the last 3 hours figuring it out on myself :D )

BEWARE THE CODE BELOW IS UNTESTED - MAKE A BACKUP OF YOUR DATABSE BEFORE RUNNING IT

This gets the old data out, matches it against the migration files, alters the table and inserts the data in the new format. Hopefully in a more or portable way.

Note: This does not handle the case when there is a old-style migration table but without any rows, since there's currently no abstract way for getting the table description via Sequelize.

var migration = sequelizeInstance.getQueryInterface(),
    DataTypes = sequelizeInstance.constructor,
    umzug = new Umzug({

        storage: 'sequelize',

        storageOptions: {
            sequelize: sequelizeInstance,
        },

        migrations: {
            params: [migration, DataTypes],
            path: migrations,
            pattern: /\.js$/
        }

    });

// Check if we need to upgrade from the old sequlize migration format
sequelizeInstance.query('SELECT * FROM "SequelizeMeta";', {
    raw: true

}).then(function(raw) {

    var rows = raw[0];
    if (rows.length && rows[0].hasOwnProperty('id')) {

        var migrationFiles = fs.readdirSync(migrations),
            data = rows.map(function(row) {
                return migrationFiles.filter(function(f) {
                    return f.substring(0, row.to.length) === row.to;

                })[0];
            });

        // Drop the existing migration data
        return sequelizeInstance.query('DELETE FROM "SequelizeMeta";', null, {
            raw: true

        // Update the table format
        }).then(function() {
            return migration.renameColumn('SequelizeMeta', 'to', 'name').then(function() {
                return migration.removeColumn('SequelizeMeta', 'from');

            }).then(function() {
                return migration.removeColumn('SequelizeMeta', 'id');
            });

        // Insert data in the new migration format
        }).then(function() {

            var MetaModel = umzug.storage.options.storageOptions.model;

            return bluebird.all(data.map(function(migrationName) {
                return MetaModel.create({
                    name: migrationName
                });
            }));

        });

    } else {
        // TODO check the table layout in case it's empty
    }

}, function() {
    return true;

}).then(function() {

    umzug[method]().then(function() {
        grunt.log.ok('Migration complete!');
        done();

    }, done);

});

BonsaiDen avatar Feb 17 '15 13:02 BonsaiDen

So just to clarify this: Each migration function (that is up and down) will be called with up to 3 arguments: migration, DataTypes, callback. If you provide a function that uses all three arguments, you will have to call callback to tell umzug, that you migration has been finished. Functions that with less than 3 arguments are supposed to return a Promise. Anyways, to come back to the initial question: It's the first argument you are looking for. I really wonder if there is no documentation about that. http://sequelize.readthedocs.org/en/latest/docs/migrations/#skeleton

sdepold avatar Feb 18 '15 07:02 sdepold

@BonsaiDen You are actually right about the fancy wrapper stuff. There used to be a thing called migrator which was wrapping the functions of the query interface. This is no longer the case. Instead we are directly passing the queryinterface into the migration as the first argument.

sdepold avatar Feb 18 '15 07:02 sdepold

Closing old issue as inactivity for a while.

jukkah avatar Sep 14 '16 12:09 jukkah

https://github.com/sequelize/umzug/issues/17#issuecomment-74652312 Should be in the readme

stephan-nordnes-eriksen avatar Mar 08 '17 13:03 stephan-nordnes-eriksen