fix: 修复在Migrate中,且db.DryRun=true时,GetColumnComment方法因获取不到当前库名而报错 #28
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Bug场景与原因
有表改动(例如string型字段长度变化)时, 需要执行
db.AutoMigrate(...)
.在交互式的命令行程序中,一般设置
db.DryRun = true
并执行db.AutoMigrate(...)
, 先打印出SQL语句, 人为确认没啥问题后, 重设db.DryRun = false
再次执行db.AutoMigrate(...)
.本库中的
Migrator.CurrentDatabase()
方法在db.DryRun = true
时, 因不实际执行查询逻辑而报错并奔溃, 日志如下:一般情况下gorm官方对
DryRun
有相应的处理逻辑:分场景使用 db session:
queryTx
与execTx
, 在执行信息查询时使用queryTx
, 在执行表结构调整时使用execTx
.本库的
Migrator.MigrateColumn()
方法中, 使用默认session:execTx
间接调用Migrator.CurrentDatabase()
查询当前库名, 因此会报错并奔溃.解决方案
方案一: 在内部方法
Migrator.GetColumnComment()
中不直接调用Migrator.CurrentDatabase()
, 改成使用queryTx
直接查询出当前库名. 详情见本次提交的代码改动方案二: 修改
Migrator.CurrentDatabase()
方法, 创建并使用queryTx
来查询当前库名. 如下所示: