How to do knex.js migrations?

前端 未结 6 1549
天命终不由人
天命终不由人 2021-02-01 19:39

I\'m still not sure how to do my migrations with knex. Here is what I have so far. It works on up, but down gives me FK constraint error even though fo

6条回答
  •  情书的邮戳
    2021-02-01 20:02

    jedd.ahyoung is correct. You don't need to limit your connection pool to 1. You just need to chain your promises so they are not run in parallel.

    For example:

    exports.up = function(knex, Promise) {
      return removeForeignKeyChecks()
        .then(createMemberTable)
        .then(createAddressTable)
        .then(addForeignKeyChecks);
    
      function removeForeignKeyChecks() {
        return knex.raw('SET foreign_key_checks = 0;');
      }
    
      function addForeignKeyChecks() {
        return knex.raw('SET foreign_key_checks = 1;');
      }
    
      function createMemberTable() {
        return knex.schema.createTable('Member', function (table) {
          table.bigIncrements('id').primary().unsigned();
          table.string('email',50);
          table.string('password');
    
          /* CREATE FKS */
          table.bigInteger('ReferralId').unsigned().index();
          table.bigInteger('AddressId').unsigned().index().inTable('Address').references('id');
        });
      }
    
      function createAddressTable() {
        return knex.schema.createTable('Address', function (table) {
          table.bigIncrements('id').primary().unsigned();
          table.index(['city','state','zip']);
    
          table.string('city',50).notNullable();
          table.string('state',2).notNullable();
          table.integer('zip',5).unsigned().notNullable();
        });
      }
    };
    

    Also I may be missing something but it looks like you won't need to remove and then reinstate the foreign key checks if you create the address table before the member table.

    Here's how the final code would look:

    exports.up = function(knex, Promise) {
      return createAddressTable()
        .then(createMemberTable);
    
      function createMemberTable() {
        return knex.schema.createTable('Member', function (table) {
          table.bigIncrements('id').primary().unsigned();
          table.string('email',50);
          table.string('password');
    
          /* CREATE FKS */
          table.bigInteger('ReferralId').unsigned().index();
          table.bigInteger('AddressId').unsigned().index().inTable('Address').references('id');
        });
      }
    
      function createAddressTable() {
        return knex.schema.createTable('Address', function (table) {
          table.bigIncrements('id').primary().unsigned();
          table.index(['city','state','zip']);
    
          table.string('city',50).notNullable();
          table.string('state',2).notNullable();
          table.integer('zip',5).unsigned().notNullable();
        });
      }
    };
    

提交回复
热议问题