简体   繁体   English

如何使用 knex 迁移更改 postgresql 数据库中列的数据类型?

[英]How to change datatype of a column in postgresql database using knex migration?

I have a column in a postgresql database table.我在 postgresql 数据库表中有一个列。 Currently it is of datatype INTEGER, I want to change it to JSONB datatype.目前它的数据类型为 INTEGER,我想将其更改为 JSONB 数据类型。

  • Maybe this topic can answer your question: Modify column datatype in Knex migration script也许这个话题可以回答你的问题: 修改 Knex 迁移脚本中的列数据类型

  • For more detail you can have a look at the knex documentation: https://knexjs.org/#Schema-alter有关更多详细信息,您可以查看 knex 文档: https ://knexjs.org/#Schema-alter

  • Knex supports you to write alter column as the way you create column. Knex 支持您按照创建列的方式编写更改列。 The different is that you have to use alterTable() to get alterTable builder in knex that will support modifing your database information.不同之处在于您必须使用 alterTable() 在 knex 中获取支持修改数据库信息的 alterTable builder。

  • Or else you can take a look at my code:或者你可以看看我的代码:

    • Assume that I have a previous migration run before like this:假设我之前运行过这样的迁移:
     export function up(knex) { return knex.schema.createTable('users', table => { table.increments('id').primary('id'); table.string('username').notNullable().unique('username'); table.string('fullName'); table.string('email'); table.string('password'); table.timestamps(true, true); }); }
    • And I want to modify column email so that I will use alterTable to modify the column.我想修改列电子邮件,以便我将使用 alterTable 修改列。 Note: Keep in mind that when you do migration with knex postgresql you may be failed because of some reasons so that you should use transaction for making sure that the failure will not effect to your database.注意:请记住,当您使用 knex postgresql 进行迁移时,您可能会因为某些原因而失败,因此您应该使用事务来确保失败不会影响您的数据库。 But with migration of mysql, you will no need to use this because knex mysql do support transaction while dealing with migration.但是对于mysql的迁移,您将不需要使用它,因为knex mysql在处理迁移时确实支持事务。
     export async function up(knex) { const transaction = await knex.transaction(); try { await transaction.schema.alterTable('users', table => { table.string('email').notNullable().alter(); }); await transaction.commit(); } catch (error) { await transaction.rollback(); } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM