如何做knext .js迁移



我仍然不确定如何使用knex进行迁移。这是我目前所知道的。它适用于up,但down给我FK约束错误,即使foreign_key_checks = 0。

exports.up = function(knex, Promise) {
  return Promise.all([
    knex.raw('SET foreign_key_checks = 0;'),
    /* CREATE Member table */
    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');
    }),
    /* CREATE Address table */
    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();
    }),
    knex.raw('SET foreign_key_checks = 1;')
  ]);
};
exports.down = function(knex, Promise) {
  return Promise.all([
    knex.raw('SET foreign_key_checks = 0;'),
    knex.schema.dropTable('Address'),
    knex.schema.dropTable('Member'),
    knex.raw('SET foreign_key_checks = 1;')
  ]);
};

阿扬是对的。您不需要将连接池限制为1。你只需要把你的承诺链接起来,这样它们就不会并行运行了。

例如:

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();
    });
  }
};

我也可能错过了一些东西,但看起来你不需要删除,然后恢复外键检查,如果你创建成员表之前的地址表。

下面是最终代码的样子:
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();
    });
  }
};

发现由于连接池而无法工作。它将使用不同的连接来运行每个迁移任务,这将导致不能正确设置外键检查。设置

pool:{
  max:1
}

我通过使用事务解决了这个问题

transation.js

module.exports = function transaction(fn) {
    return function _transaction(knex, Promise) {
        return knex.transaction(function(trx) {
            return trx
                .raw('SET foreign_key_checks = 0;')
                .then(function() {
                    return fn(trx, Promise);
                })
                .finally(function() {
                    return trx.raw('SET foreign_key_checks = 1;');
                });
        });
    };
}

移民文件

var transaction = require('../transaction');
function up(trx, Promise) {
    return trx.schema
       .createTable('contract', function(table) {
           table.boolean('active').notNullable();                                              
           table.integer('defaultPriority').unsigned().references('priority.id');                             
           table.integer('defaultIssueStatus').unsigned().references('issueStatus.id');
           table.integer('owner').notNullable().unsigned().references('user.id'); 
       })
       .createTable('user', function (table) {
           table.increments('id').primary();
           table.datetime('createdAt');
           table.datetime('updatedAt');
           table.string('phoneNumber').notNullable().unique();
           table.string('password').notNullable();            
           table.string('name').notNullable().unique();       
           table.string('email');                             
           table.string('status');                            
           table.string('roles').defaultTo('user');           
           table.integer('contract').unsigned().references('contract.id');
       });
}
function down(trx, Promise) {
    return trx.schema
        .dropTable('contract')
        .dropTable('user');
}
exports.up = transaction(up);
exports.down = transaction(down);

inTable()应放在references()之后:

inTablecolumn.inTable(table)

在调用column.references后设置外键列所在的table

文档。

我想我应该更新一下,因为有一些添加到Javascript,使这相当容易一点。knex仍然要求您返回Promise,但在Promise中,您可以做很多事情来清理与表的创建/修改相关的代码。我的偏好是使用async/awaitPromise.all的组合。

exports.up = function(knex, Promise) {
    return new Promise(async (resolve, reject) => {
        try {
            await Promise.all([
                knex.schema.createTable('videos', table => {
                    table.increments('id');
                    table.string('title');
                    table.string('director');
                    table.json('meta');
                }),
                knex.schema.createTable('books', table => {
                    table.increments('id');
                    table.string('title');
                    table.string('author');
                    table.json('meta');
                })
            ]);
            console.log('Tables created successfully');
            resolve();
        } catch(error) {
            reject(error);
        }
    })
}

如果你喜欢单独创建每个表,那么我只使用async/await

exports.up = function(knex, Promise) {
    return new Promise(async (resolve, reject) => {
        try {
            await knex.schema.createTable('videos', table => {
                table.increments('id');
                table.string('title');
                table.string('director');
                table.json('meta');
            });
            console.log('videos table created successfully!');
            await knex.schema.createTable('books', table => {
                table.increments('id');
                table.string('title');
                table.string('author');
                table.json('meta');
            });
            console.log('books table created successfully!');
            resolve();
        } catch(error){
            reject(error);
        }
    })
}

这使事情更干净,不需要你把一堆then串起来,或者把它们包装在周围的函数中。您只需为每个表的创建解析await,然后封装它们解析Promise !为async/await加油!

down迁移中删除表也可以遵循这个模式。只需将knex.schema.createTable语句替换为knex.schema.dropTable语句。

作为最干净的方法,我建议在您的迁移文件中包括以下内容:

exports.up = function (knex) {
  return Promise.all([
    knex.schema.createTable('users', function (table) {
      table.increments('id')
      table.string('username').notNullable()
      table.string('password').notNullable()
      table.string('service').notNullable()
      table.text('cookies')
      table.enu('status', ['active', 'disabled', 'need_login', 'failed']).defaultTo('need_login').notNullable()
      table.datetime('last_checked')
      table.timestamps()
    }),
    knex.schema.createTable('products', function (table) {
      table.increments()
      table.integer('user_id').unsigned().notNullable()
      table.string('title')
      table.decimal('price', 8, 2)
      table.text('notes')
      table.enu('status', ['to_publish', 'published', 'hidden', 'not_found']).notNullable()
      table.timestamps()
      table.foreign('user_id').references('id').inTable('users')
    }),
    knex.schema.createTable('messages', function (table) {
      table.increments()
      table.integer('user_id').unsigned().notNullable()
      table.integer('product_id').unsigned().notNullable()
      table.boolean('incoming')
      table.boolean('unread')
      table.text('text')
      table.timestamps()
      table.foreign('user_id').references('id').inTable('users')
      table.foreign('product_id').references('id').inTable('products')
    })
  ])
}
exports.down = function (knex) {
  return Promise.all([
    knex.schema.dropTable('messages'),
    knex.schema.dropTable('products'),
    knex.schema.dropTable('users')
  ])
}