首页 > 解决方案 > 带有 Sqlite 的 Knex 是否需要销毁才能运行多个查询?

问题描述

我有一个脚本,我正在尝试使用 Knex 和 Sqlite3 生成我的数据库模式。它如下所示:

schema.js

const log = require('electron-log');
const app = require('electron').remote.app;
let knex = require('knex')({
    client: 'sqlite3',
    connection: {
        filename: app.getPath('userData') + '/warframeData.db',
    },
});

async function create() {
    log.debug('Creating schema.');
    await createSchemaVersion()
        .then(createRelicTable)        
        .catch((err) => log.debug(err));
}

function createSchemaVersion() {
    log.debug('calling Create Schema Version');
    return knex.schema
        .createTableIfNotExists('schemaVersion', function (table) {
            table.string('name').unique().notNullable();
            table.integer('major').notNullable();
            table.integer('minor').notNullable();
            table.integer('patch').notNullable();
        })
        .then(() => {
            log.debug('Table schemaVersion created');
        })
        .catch((err) => {
            log.error('Error creating table schemaVersion', err);
        })
}

function createRelicTable() {
    log.debug('calling Create Relics');
    return knex.schema
        .createTableIfNotExists('relics', function (table) {
            table.string('name').unique().notNullable().primary();
            table.integer('tradable').notNullable();
            table.string('url').notNullable();
            table.string('image').notNullable();
            table.integer('vaulted').notNullable();
        })
        .then(() => {
            log.debug('Table relics created');
        })
        .catch((err) => {
            log.error('Error creating table relics', err);
        });

当我运行它时,数据库被创建,schemaVersion 表被创建,但随后它挂起。日志只产生这个:

[2020-06-09 10:56:17.073] [debug] Creating schema.
[2020-06-09 10:56:17.074] [debug] calling Create Schema Version

请注意,无论是还是then永远都不会通过。catchcreateSchemaVersion

如果我在.finally(() => knex.destroy())每个 knex 操作中添加一个 - 那么一切正常,并且我得到了我所期望的完整日志,但是由于 knex 对象已被破坏,遗物创建显然会爆炸。所以,如果我在每个函数中重新制作 knex 对象 - 那么一切正常。

但这似乎是错误的。看来我应该能够重新使用 knex 对象。

这里发生了什么?您真的每次都必须销毁/重新创建 knex 对象吗?

标签: knex.jsnode-sqlite3

解决方案


对于后来偶然发现的任何人,这是因为我是从电子渲染器进程而不是 main 调用这个脚本。我找不到任何错误或消息 - 但在另一位开发人员的建议下,我尝试从 Main.js 调用相同的脚本,它工作得很好。

这可能是一个新手 Electron 的错误——但这就是我所拥有的。


推荐阅读