简体   繁体   中英

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

I have a column in a postgresql database table. Currently it is of datatype INTEGER, I want to change it to JSONB datatype.

  • Maybe this topic can answer your question: Modify column datatype in Knex migration script

  • For more detail you can have a look at the knex documentation: https://knexjs.org/#Schema-alter

  • Knex supports you to write alter column as the way you create column. The different is that you have to use alterTable() to get alterTable builder in knex that will support modifing your database information.

  • 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. 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. But with migration of mysql, you will no need to use this because knex mysql do support transaction while dealing with migration.
     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(); } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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