【问题标题】:How to change datatype of a column in postgresql database using knex migration?如何使用 knex 迁移更改 postgresql 数据库中列的数据类型?
【发布时间】:2021-07-19 05:20:00
【问题描述】:

我在 postgresql 数据库表中有一个列。目前是INTEGER数据类型,我想改成JSONB数据类型。

【问题讨论】:

    标签: sql reactjs postgresql knex.js


    【解决方案1】:
    • 也许这个话题可以回答你的问题:Modify column datatype in Knex migration script

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

    • Knex 支持您以创建列的方式编写更改列。不同的是,您必须使用 alterTable() 来获取 knex 中的 alterTable builder,该构建器将支持修改您的数据库信息。

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

      • 假设我之前运行过这样的迁移:
      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();
          }
      }
      

    【讨论】:

      猜你喜欢
      • 2018-08-05
      • 2020-06-09
      • 2013-07-27
      • 2020-03-07
      • 2018-09-16
      • 2021-07-26
      • 2021-01-08
      • 2011-11-02
      • 1970-01-01
      相关资源
      最近更新 更多