使用knex.js的规范方式似乎是创建迁移来定义模式,然后在普通节点.js代码中插入到所述模式中。
有没有办法不使用迁移?我可以从普通节点.js代码中使用knex.schema.createTable(...)
函数吗?有没有关于这种事情的文档?
编辑:我最初写这个问题是因为我认为我无法从正常的代码库中执行knex.schema.createTable(...)
函数。现在看来我根本无法从任何代码中正确使用 knex。如果我使用迁移为 SQLite3 数据库生成架构,它可以工作,但我似乎永远无法在迁移或其他方式中插入或查询数据。
我的迁移文件:
exports.up = function(knex, Promise) {
return Promise.all([
knex.schema.createTableIfNotExists('test', function(table){
console.log("creating user table");
table.increments('id');
table.text('test');
})
]);
};
exports.down = function(knex, Promise) {
return Promise.all([
knex.schema.dropTableIfExists('test')
]);
};
knexfile.js:
module.exports = {
development: {
client: "sqlite3",
connection: {
filename: "devel.db"
},
useNullAsDefault: true
},
deployment: {
client: "sqlite3",
connection: {
filename: "deploy.db"
},
useNullAsDefault: true
}
};
我写了一个摩卡/柴测试:
const chai = require("chai");
var knex = require("knex")({ client: "sqlite3", connection: { filename: "devel.db" }, useNullAsDefault: true });
var expect = chai.expect;
// The tests.
describe("db", ()=> {
it("Simple connect, query, and destroy.", ()=> {
knex('test').insert({ test: 'wow' })
.catch(function(e){
console.error(e);
});
});
});
迁移工作正常。 在测试中,您需要返回 knex 对象才能执行它。
describe("db", ()=> {
it("Simple connect, query, and destroy.", ()=> {
return knex('test').insert({ test: 'wow' })
.catch(function(e){
console.error(e);
});
});
});
在回答实际问题时,是的,你可以。 该代码类似于迁移代码,但需要调用 then() 或 catch() 来执行它。 Knex 文档对此进行了介绍,但还不是那么清楚。 下面是在迁移文件外部修改架构的示例:
knex.schema.table('test', function (table) {
table.string('foo');
table.string('baa');
})
.catch(function(err) {
console.log(err);
});
我想不出很多时候在没有迁移的情况下修改数据库架构会更好,但这取决于您的应用程序。