使用迁移API时,Knex迁移无法正常工作

5

我刚接触knex迁移,过去两天一直在努力让它工作,但是没有任何进展。我正在试图使用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) {

};

然后从我的代码中初始化Knex对象:
var knex = Knex({
        client:'sqlite3',
        connection:{
            filename: './knex.sqlite'
        }
    });

然后我执行迁移:

knex.migrate.latest().then(()=>{
        // console.log()
    }).catch(err =>{
        // 
    });

但是什么都没有发生。我的迁移文件从来没有被执行,也没有任何错误或警告信息。所以我不知道从哪里开始寻找问题。当我查看我的sqlite数据库时,我可以看到已经创建了表knex_migrationsknex_migrations_locksqlite_sequence

那么我在这里做错了什么?有什么我漏掉的东西吗? 感谢任何建议。


从数据库中删除knex_migrations和knex_migrations_lock表并重新运行。在catch块中使用console.log打印错误信息。 - Fazal Rasel
你的目录结构和knexfile文件怎么样?可能是你的迁移文件放错了文件夹吗? - Mikael Lepistö
是的,我的迁移文件夹不在项目根目录中,而是在子文件夹中。但我通过配置选项中的migrations.direction选项确保指向正确的文件夹。此外,我通过调试步入源代码,可以看到Knex找到了我的文件夹并列出了其内容...但由于某些原因,它没有运行迁移... - TheSoul
没有属性migrations.direction。如果您在调试器中执行了该代码,应该能够看到为什么找不到迁移文件。无论如何,在这个问题中提供的数据是无法帮助您更多的。尝试编写一个示例Knex应用程序,当您使其正常工作时,请查明您在真实应用程序上所做的不同之处。 - Mikael Lepistö
但是有 migrations.directory 属性。请使用它。 - Aleksei Potapkin
2个回答

5

不必使用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();
});

原问题中存在两个问题:

  1. 没有指定迁移目录 - 在这种情况下,Knex不会聪明地抛出错误,而只是什么也不做。很可能Knex使用的默认值不正确,因此最好进行指定。

  2. 缺少knex.destroy()。在这种情况下,脚本永远不会退出,因为Knex保持数据库上的开放句柄,所以它看起来像是卡住了没反应。

以上脚本还输出更多日志信息以查看发生了什么。


-1

Knex 迁移应该由 Knex CLI 运行,详见:https://knexjs.org/#Migrations

根据您的代码描述,我发现了一个奇怪的问题:

knex.migrate 实际上是未定义的,它不是 knex 的属性。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接