簡體   English   中英

如何使用 knex 遷移更改 postgresql 數據庫中列的數據類型?

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

我在 postgresql 數據庫表中有一個列。 目前它的數據類型為 INTEGER,我想將其更改為 JSONB 數據類型。

  • 也許這個話題可以回答你的問題: 修改 Knex 遷移腳本中的列數據類型

  • 有關更多詳細信息,您可以查看 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(); } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM