Describe the feature
实现手动灵活添加索引的 AddIndex 和 AddUniqueIndex 方法,像V1那样。
Motivation
旧项目使用gormV1,像下面这样添加索引:
a.DB.Model(&models.Like{}).Where("deleted_at IS NULL").AddUniqueIndex("like_idx_post_id_id", "post_id", "id")
现在想升级到V2,V2似是使用Migrator.CreateIndex, 但是索引这方面碰到了点问题:
- struct里要添加tag, 若在field上add多个不同索引;或者多个fields上添加same index 来建复合索引,结果tag会变得很长和很不直观,可读性降低。
- 若不另外添加index name,只添加index或uniqueIndex,然后CreateIndex时会查询有index的fields统一建立索引,也不能创多个自定义索引。
- 假如要添加的索引包括了gorm.Model里的id或者created_at等字段,那是否需要修改这些fields的tag?
- 如上代码中,若要添加索引的条件,目前貌似不能用。
因为要直观知道添加了哪些uniqueIndex和index 比较重要,而且数量也很大,都改成tag感觉杂乱不直观而且容易出问题。现在要满足以前的需求只能用原声sql创建,然而这次升级v2就是想优化V1 batchCreate时手动拼sql的问题。
万分感谢🙏!
Related Issues
https://github.com/go-gorm/gorm/issues/5075
Comment From: jinzhu
Hi
We are not going to bring back the AddIndex, AddUniqueIndex method, maybe you can create a customized model only for the migration with tag?
Thank you.
Comment From: XBreath
Hi
We are not going to bring back the
AddIndex,AddUniqueIndexmethod, maybe you can create a customized model only for the migration with tag?Thank you.
你好! 感谢回复! 能举个例子吗?
Comment From: yangcheng
Hi
We are not going to bring back the
AddIndex,AddUniqueIndexmethod, maybe you can create a customized model only for the migration with tag?Thank you.
@jinzhu can you explain the rationale for this choice? Index is not part of data model, but rather an optimization for particular database implementation/version. I understand support meta-data like index can cover majority use case but often we still need to fine-tune index. Thanks
Comment From: jinzhu
Suggest to write following code in your migration files, so you can use gorm with other migration tools like: https://github.com/golang-migrate/migrate
type UserForMigration struct {
Name string `gorm:"size:255;index:idx_name"`
}
// Create index for Name field
db.Table("uses").Migrator().CreateIndex(&UserForMigration{}, "Name")