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



我在postgresql数据库表中有一列。目前它的数据类型是INTEGER,我想将其更改为JSONB数据类型。

  • 也许这个主题可以回答你的问题:在Knex迁移脚本中修改列数据类型

  • 有关更多详细信息,您可以查看knex文档:https://knexjs.org/#Schema-更改

  • Knex支持您按照创建列的方式编写alter列。不同的是,您必须使用alterTable((在knex中获得alterTable生成器,该生成器将支持修改数据库信息。

  • 或者你可以看看我的代码:

    • 假设我以前运行过一次迁移,如下所示:
    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);
    });
    }
    
    • 我想修改列电子邮件,以便使用alterTable来修改列。注意:请记住,当您使用knex postgresql进行迁移时,您可能会因为某些原因而失败,因此您应该使用事务来确保失败不会影响您的数据库。但是对于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();
    }
    }
    

最新更新