我正在寻找一个迁移字符串来为枚举列类型添加一个新字符串。我正在尝试将gamma
添加到service
列。
我尝试使用下面的代码。这会发生冲突,因为表和列已经存在。
const table = 'user_associations'
export function up (knex, Promise) {
return knex.schema.table(table, function (table) {
table.enu('service', ['alpha', 'beta', 'gamma']).notNullable()
})
}
export function down (knex, Promise) {
return knex.schema.table(table, function (table) {
table.enu('service', ['alpha', 'beta']).notNullable()
})
}
const tableName = 'user_associations'
export function up (knex, Promise) {
let existRows;
return knex.select()
.from(tableName)
.then((rows) => {
existRows = rows
return knex.schema.table(tableName, (table) => table.dropColumn('service'))
})
.then(() => knex.schema.table(tableName, (table) => table.enu('service', ['alpha', 'beta', 'gamma']).notNullable().default('alpha')))
.then(() => {
return Promise.all(existRows.map((row) => {
return knex(tableName)
.update({ service: row.service })
.where('id', row.id)
}))
})
}
export default down(kenx, Promise) {
let existRows;
return kenx.select()
.from(tableName)
.then((rows) => {
existRows = rows
return knex.schema.table(tableName, (table) => table.dropColumn('service'))
})
.then(() => knex.schema.table(tableName, (table) => table.enu('service', ['alpha', 'beta']).notNullable().default('alpha')))
.then(() => {
return Promise.all(existRows.map((row) => {
return knex(tableName)
.update({ service: row.service === 'gamma' ? 'alpha' : row.service })
.where('id', row.id)
}))
})
}
截至2018-09-05,这仍然是一个悬而未决的问题:https://github.com/tgriesser/knex/issues/1699(我相信你打开了它!)。如果您正在使用PostgreSQL,那么这就是我要做的:
$ psql
> \c ...
> \dt
看到所有表格> \d user_associations
查看该表的所有信息user_associations_service_check
然后回到你的迁移中:
exports.up = knex =>
knex.raw(`
ALTER TABLE ONLY user_associations
DROP CONSTRAINT user_associations_service_check;
ALTER TABLE ONLY user_associations
ADD CONSTRAINT user_associations_service_check
CHECK ("service" = ANY (ARRAY['alpha'::text, 'beta'::text, 'gamma'::text]));
`)
exports.down = knex =>
knex.raw(`
ALTER TABLE ONLY user_associations
DROP CONSTRAINT user_associations_service_check;
ALTER TABLE ONLY user_associations
ADD CONSTRAINT user_associations_service_check
CHECK ("service" = ANY (ARRAY['alpha'::text, 'beta'::text));
`)
关于你上面链接的knexjs问题的评论有一个聪明的实用功能来完成这个:https://github.com/tgriesser/knex/issues/1699#issuecomment-402603481。