sql - 如何使用 knex 迁移更改 postgresql 数据库中列的数据类型?
问题描述
我在 postgresql 数据库表中有一个列。目前它的数据类型为 INTEGER,我想将其更改为 JSONB 数据类型。
解决方案
也许这个话题可以回答你的问题: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(); } }
推荐阅读
- xslt-1.0 - 当 position() 不可靠时,在除最后一个元素之外的所有元素之后插入分页符
- c# - Awesomefont 未在服务器上显示,在本地显示
- ruby-on-rails - 没有这样的目录 ruby.exec Errno:ENONT
- symfony - 保留 SVG 图像链接 TCPDF/FPDI 和 Ghostscript
- html - 边缘附有一些列的网格
- python - VSCode:Python,意外参数警报
- sql - DataGridView 无法使用临时表检索存储过程
- python - Python Selenium - 在列表中查找项目
- css - 更改图标的大小
- html - VBA HTML 选择下拉选项