如何编写 knex 迁移文件以自动更新现有数据库
How how do I write a knex migration file to automatically update existing Database
我想为以下查询创建迁移文件
`insert into table1(column1)
select o.name from original_table as o`
`update original_table as o
set new_column = (select t1.id from table1 as t1
where t.column1 = o.old_column)`
到目前为止我想到了这个。第一部分有效,但我坚持使用第二部分
`exports.up = function (knex, Promise) {
return Promise.resolve()
.then(() => knex('original_table').select('old_column'))
.then((rows) => knex('table1').insert(rows))
.then(() => knex('table1 as t').select(['t.column1',
'column2']).join('original_table
as o', 'o.old_column', 't.column2'))
.then((rows) => knex('original_tableas
o').whereIn('original_table.old_column', rows.column2).update('column2',
rows.column1))
};
exports.down = function (knex) {
return Promise.resolve()
.then(() => console.log("Deletes updated records"));
};`
提前致谢。
第一个查询实际上用 knex 形成很不方便,但是 knex.raw
几乎可以做任何事情。以下是我能想到的最有效的写法:
exports.up = async (knex) => {
// insert into table1(column1) select o.name from original_table as o
await knex.raw('insert into ?? (??) ??', ['table1', 'column1', knex('original_table').select('name')]);
// update original_table as o set
// new_column = (
// select t1.id from table1 as t1 where t1.column = o.old_column
// )
await knex('original_table as o').update({
new_column: knex('table1 as t1').select('id').where('t1.column', 'o.old_column')
});
}
我想为以下查询创建迁移文件
`insert into table1(column1)
select o.name from original_table as o`
`update original_table as o
set new_column = (select t1.id from table1 as t1
where t.column1 = o.old_column)`
到目前为止我想到了这个。第一部分有效,但我坚持使用第二部分
`exports.up = function (knex, Promise) {
return Promise.resolve()
.then(() => knex('original_table').select('old_column'))
.then((rows) => knex('table1').insert(rows))
.then(() => knex('table1 as t').select(['t.column1',
'column2']).join('original_table
as o', 'o.old_column', 't.column2'))
.then((rows) => knex('original_tableas
o').whereIn('original_table.old_column', rows.column2).update('column2',
rows.column1))
};
exports.down = function (knex) {
return Promise.resolve()
.then(() => console.log("Deletes updated records"));
};`
提前致谢。
第一个查询实际上用 knex 形成很不方便,但是 knex.raw
几乎可以做任何事情。以下是我能想到的最有效的写法:
exports.up = async (knex) => {
// insert into table1(column1) select o.name from original_table as o
await knex.raw('insert into ?? (??) ??', ['table1', 'column1', knex('original_table').select('name')]);
// update original_table as o set
// new_column = (
// select t1.id from table1 as t1 where t1.column = o.old_column
// )
await knex('original_table as o').update({
new_column: knex('table1 as t1').select('id').where('t1.column', 'o.old_column')
});
}