首页 > 解决方案 > knex.js - 动态模式名​​称迁移失败

问题描述

环境

漏洞

我正在尝试使用ava. 众所周知,ava为每个测试文件生成不同的节点进程。

为了使测试隔离,我需要重新创建我的数据库并在所有测试文件中运行迁移。我开始引导并得到以下脚本:

import test from 'ava';
import cuid from 'cuid';
import knexFactory from 'knex';
import knexFile from './knexfile';

const knex = knexFactory(knexFile.development);

test.before(async t => {
  const schemaName = `foo_${cuid()}`;

  await knex.raw(`CREATE SCHEMA ${schemaName}`);

  try {
    await knex.migrate.latest({ schemaName });;
  } catch (err) {

  }

  Object.assign(t.context, { schemaName });
});

test.after.always(async t => {
  const { schemaName } = t.context;
  await knex.raw(`DROP SCHEMA ${schemaName}`);
});

test('foo', () => {})

但是,我遇到了以下错误:

迁移文件“20190205110315_create_users_table.js”失败
迁移失败并出现错误:创建表usersidint unsigned not null auto_increment 主键,emailvarchar(255),password文本) - 表“用户”已经存在

发生的情况是.migrate.latest()调用忽略了它schemaName的参数,并且它针对文件中定义的配置运行knexfile.js,即实际数据库。

迁移文件非常简单:

exports.up = function(knex, Promise) {
  return knex.schema.createTable('users', table => {
    table.increments();
    table.string('email');
    table.text('password');
  })
};

exports.down = function(knex, Promise) {
  return knex.schema.dropTable('users');
};

标签: node.jsknex.jsava

解决方案


推荐阅读