The*_*oul 5 migration node.js knex.js
我是 knex 迁移的新手,在过去的 2 天里我一直在努力让它工作,但没有任何反应。我正在尝试使用该knex.migration对象以编程方式运行我的迁移。
首先使用 cli,我在迁移目录中创建一个迁移文件。这是它的内容:
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) {
};
Run Code Online (Sandbox Code Playgroud)
然后从我的代码中初始化 Knex 对象:
var knex = Knex({
client:'sqlite3',
connection:{
filename: './knex.sqlite'
}
});
Run Code Online (Sandbox Code Playgroud)
然后我执行迁移:
knex.migrate.latest().then(()=>{
// console.log()
}).catch(err =>{
//
});
Run Code Online (Sandbox Code Playgroud)
但绝对没有任何反应。我的迁移文件从未执行,并且没有错误或警告消息。所以我不知道从哪里开始寻找问题。当我查看 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();
});
Run Code Online (Sandbox Code Playgroud)
原问题有两个问题:
未指定迁移目录 - 在这种情况下 Knex 并不智能,不会执行任何操作而不是抛出错误。Knex 使用的默认值很可能不正确,因此最好指定它。
knex.destroy()失踪。在这种情况下,脚本永远不会退出,因为 Knex 保持数据库上的打开句柄,因此它看起来就像卡住了什么都不做。
上面的脚本还输出更多日志信息以查看到底发生了什么。
Sin*_*nux -1
Knex 迁移应该由Knex CLI\xef\xbc\x8cFYI 运行: https: //knexjs.org/#Migrations
正如您的代码所描述的,我发现了一个奇怪的问题:
\n\nknex.migrate 实际上是未定义的,它不是 knex 的属性。
\n| 归档时间: |
|
| 查看次数: |
10306 次 |
| 最近记录: |