javascript - 如何使用 1 knex 脚本创建整个数据库的迁移?
问题描述
在我的数据库中,我有大约 50 张桌子。每张桌子都有created_at
和updated_at
。当然,我可以创建 50 个迁移,但会有类似的。是否有机会创建knex
可以对整个数据库进行 50 次迁移的脚本?
这是代码示例:
exports.up = function(knex, Promise) {
return knex.schema.alterTable("balance", table => {
table.timestamp("created_at").defaultTo(knex.fn.now()).alter()
table
.timestamp("updated_at")
.defaultTo(knex.raw("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")).alter()
})
};
exports.down = function(knex, Promise) {
return knex.schema.alterTable("balance", table => {
table.dateTime("created_at").defaultTo(null).alter()
table.dateTime("updated_at").defaultTo(null).alter()
})
};
Balance是表的名称,所以我必须创建大约 50 个迁移,只更改数据库的名称。是否可以仅使用 1 个 knex 脚本使一切变得更容易?
感谢您的回答!
解决方案
就像这样:
const showList = await knex.raw(
`SELECT table_name FROM information_schema.tables WHERE table_schema = 'your_db';`)
for (const item of showList[0]) {
await knex.schema.alterTable(`${item.table_name}`, table => {
table.timestamp("created_at").defaultTo(knex.fn.now()).alter()
table
.timestamp("updated_at")
.defaultTo(knex.raw("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")).alter()
})
}
推荐阅读
- prometheus - 普罗米修斯速率函数如何使用的问题?
- elixir - Elixir 遍历一个列表并将其中的值附加到一个新列表中
- javascript - 在 NestJS 嵌套模式中忽略 @Prop 和 mongoose 选项
- ruby-on-rails - Carrierwave 上传文件将文件保存到 AWS 但重新加载后数据不保留
- oracle - 使用 PL/SQL SDK Dbms_cloud 从 MinIO 获取存储桶列表
- python - 如何运行 CatBoostClassifier?
- php - 使用 SMTP PHPMailer 将不同的消息发送到不同的电子邮件帐户
- vue.js - 部署asp.net core + vue.js 环境变量设置
- azure - Azure CI/CD 不承认 Wix 工具集安装项目的项目设置
- coq - Coq:消除`forall`?