Search code examples
javascriptnode.jspostgresqldatabase-migrationknex.js

How to chain promises inside a knex.js migration


session-pg-simple requires a table to be created for storing sessions, I want to add this table to my knex.js migration script.

CREATE TABLE "session" (
  "sid" varchar NOT NULL COLLATE "default",
    "sess" json NOT NULL,
    "expire" timestamp(6) NOT NULL
)
WITH (OIDS=FALSE);

ALTER TABLE "session" ADD CONSTRAINT "session_pkey" PRIMARY KEY ("sid") NOT DEFERRABLE INITIALLY IMMEDIATE;

CREATE INDEX "IDX_session_expire" ON "session" ("expire");

This above is the table creation script from https://github.com/voxpelli/node-connect-pg-simple/blob/HEAD/table.sql

exports.up = function (knex) {
  return Promise.all([
    knex.schema
      .createTable("session", function (table) {
        table.text("sid").notNullable().collate("default");
        table.json("sess").notNullable();
        table.timestamp("expire", { precision: 6 }).notNullable();
      })
      .then(
        knex.schema.raw(
          'ALTER TABLE "session" ADD CONSTRAINT "session_pkey" PRIMARY KEY ("sid") NOT DEFERRABLE INITIALLY IMMEDIATE;'
        )
      )
      .then(
        knex.schema.raw(
          'CREATE INDEX "IDX_session_expire" ON "session" ("expire");'
        )
      ),

    knex.schema.createTable("users", function (table) {
       //...
    }),
  ]);
};

The 2 .thens after the initial table creation don't run, I've tried adding them at the end of Promise.all([]) but it didn't work either. How do I implement those 2 lines into my script?


Solution

  • Promise.all don't need there, and you missed return statement in then blocks. Anyway your code can be greatly simplified, knex supports chaining, that means that you can create a chain of methods that will be called one after another:

    exports.up = function (knex) {
      return knex.schema
        .createTable("session", function (table) {
          table.text("sid").notNullable().collate("default");
          table.json("sess").notNullable();
          table.timestamp("expire", { precision: 6 }).notNullable();
        })
        .raw(
          'ALTER TABLE "session" ADD CONSTRAINT "session_pkey" PRIMARY KEY ("sid") NOT DEFERRABLE INITIALLY IMMEDIATE;'
        )
        .raw(
          'CREATE INDEX "IDX_session_expire" ON "session" ("expire");'
        )
        .createTable("users", function (table) {
           //...
        })
    };