chm*_*max 7 postgresql knex.js
现在我这样做是为了将列类型从字符串更改为枚举.有没有其他方法可以做到这一点?
是否可以将它用作knex.raw来形成这样的查询?
CREATE TYPE type AS ENUM ('disabled', 'include', 'exclude');
ALTER TABLE test_table ALTER COLUMN test_col DROP DEFAULT;
ALTER TABLE test_table ALTER COLUMN test_col TYPE logic USING(test_col::type), ALTER COLUMN test_col SET DEFAULT 'disabled'::logic;
return schema
.table('offers', function (table) {
cols.forEach(function (column) {
table.renameColumn(column, column + '_old');
});
}).then(function () {
var schema = knex.schema;
return schema.table('offers', function (table) {
cols.forEach(function (column) {
table.enum(column, ['disabled', 'include', 'exclude']).defaultTo('disabled');
});
});
}).then(function () {
return knex.select('*').from('offers');
}).then(function (rows) {
return Promise.map(rows, function (row) {
var data = {};
cols.forEach(function (column) {
data[column] = row[column+'_old'];
}, data);
return knex('offers').where('id', '=', row.id).update(data);
})
}).then(function () {
var schema = knex.schema;
return schema.table('offers',function (table) {
cols.forEach(function (column) {
table.dropColumn(column+'_old');
});
});
});
Run Code Online (Sandbox Code Playgroud)
您可以通过 knex.raw 传递有效的 SQL,因此应该可以执行以下操作:
knex.raw(`CREATE TYPE type AS ENUM ('disabled', 'include', 'exclude')`);
knex.raw(`ALTER TABLE test_table ALTER COLUMN test_col DROP DEFAULT`);
knex.raw(`ALTER TABLE test_table ALTER COLUMN test_col TYPE logic USING(test_col::type), ALTER COLUMN test_col SET DEFAULT 'disabled'::logic`);
Run Code Online (Sandbox Code Playgroud)
但是您只能使用 DDL 通过更多类似的 knex.raw 来更改枚举。另请注意,如果该列中存在不符合枚举的现有数据,则第二个 alter table 语句将失败。
| 归档时间: |
|
| 查看次数: |
2014 次 |
| 最近记录: |