我是 knex 迁移的新手,在过去的两天里,我一直在努力让它工作,但没有任何反应。我正在尝试使用 knex.migration
对象以编程方式运行我的迁移。
首先使用 cli,我在 migrations 目录中创建了一个迁移文件。这是它的内容:
exports.up = function(knex, Promise) {
return Promise.all([
knex.schema.createTable('users', function (table) {
table.increments('id').primary();
table.string('username');
table.string('password');
table.string('email');
table.string('name');
table.timestamp('date');
}),
]);
};
exports.down = function(knex, Promise) {
};
然后根据我的代码初始化 Knex 对象:
var knex = Knex({
client:'sqlite3',
connection:{
filename: './knex.sqlite'
}
});
然后我执行迁移:
knex.migrate.latest().then(()=>{
// console.log()
}).catch(err =>{
//
});
但绝对没有任何反应。我的迁移文件从未执行过,也没有错误或警告消息。所以我不知道从哪里开始寻找问题。当我查看我的 sqlite 数据库时,我可以看到已创建表 knex_migrations、knex_migrations_lock 和 sqlite_sequence。
那么我这里做错了什么?有什么我想念的吗? 感谢您的任何建议
最佳答案
不需要使用 CLI 工具。有时由于其限制而无法使用它,在这种情况下,确实可以直接使用迁移 API,如下所示:
const knex = require('knex')({
// Here goes the Knex config
});
const migrationConfig = {
directory: __dirname + './migrations',
}
console.info('Running migrations in: ' + migrationConfig.directory);
knex.migrate.latest(migrationConfig).then(([batchNo, log]) => {
if (!log.length) {
console.info('Database is already up to date');
} else {
console.info('Ran migrations: ' + log.join(', '));
}
// Important to destroy the database, otherwise Node script won't exit
// because Knex keeps open handles.
knex.destroy();
});
原题有两个问题:
未指定迁移目录 - 在这种情况下,Knex 并不智能,它只会抛出错误而不做任何事情。 Knex 使用的默认值很可能不正确,因此最好指定它。
knex.destroy()
丢失。在这种情况下,脚本将永远不会退出,因为 Knex 在数据库上保持打开的句柄,所以它看起来就像停滞不前。
上面的脚本还输出了更多日志信息以查看到底发生了什么。
关于node.js - 使用迁移 API 时 Knex 迁移不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43304267/