Muhammad Raihan Muhaimin
Muhammad Raihan Muhaimin

Reputation: 5729

Creating knex migration

I find out there is two way we can write knex migration in the migration file.

exports.up = function (knex) {
    return knex.schema
      .createTableIfNotExists('foo', function (table) {
        table.increments('id').unique();
        table.string('foo1');
        table.string('foo2');
      })
     .createTableIfNotExists('bar', function (table) {
        table.increments('bar1');
        table.string('bar2').index();
      });

Or

exports.up = function (knex) {
    return Promise.all([
      knex.schema.createTableIfNotExists('foo', function (table) {
        table.increments('id').unique();
        table.string('foo1');
        table.string('foo2');
      }),
      knex.schema.createTableIfNotExists('bar', function (table) {
        table.increments('bar1');
        table.string('bar2').index();
      })
    ]);
}

Which one is the right way of doing it?

Upvotes: 3

Views: 1378

Answers (2)

Asmita
Asmita

Reputation: 1190

This is the right way to add knex script, as Promises are the preferred way of dealing with queries in knex, as they allow you to return values from a fulfillment handler.

exports.up = function (knex) {
return Promise.all([
  knex.schema.createTableIfNotExists('foo', function (table) {
    table.increments('id').unique();
    table.string('foo1');
    table.string('foo2');
  }),
  knex.schema.createTableIfNotExists('bar', function (table) {
    table.increments('bar1');
    table.string('bar2').index();
  })
]);
}

Upvotes: 2

Muhammad Raihan Muhaimin
Muhammad Raihan Muhaimin

Reputation: 5729

Answered by Ricardo Graca at Knex's github issue page

In that case it doesn't make a difference.

You would only use the Promise based one if you require some change in a table before doing another change in another table. For example, if you needed to reference a certain table from another table and none of those tables exist yet, you would create the first table (the one that doesn't depend on anything) in a promise and then when that promise resolved you would create the second table. That way you ensure that dependencies are met.

Upvotes: 3

Related Questions