首页 > 解决方案 > 如何使用 knex 迁移更改 postgresql 数据库中列的数据类型?

问题描述

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

标签: sqlreactjspostgresqlknex.js

解决方案


  • 也许这个话题可以回答你的问题:Modify column datatype in Knex migration script

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

  • Knex 支持您以创建列的方式编写更改列。不同的是您必须使用 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();
        }
    }
    

推荐阅读