GOMR 提供了优化器、索引、备注提示支持

https://github.com/go-gorm/hints

优化器提示

  1. import "gorm.io/hints"
  2. DB.Clauses(hints.New("hint")).Find(&User{})
  3. // SELECT * /*+ hint */ FROM `users`

索引提示

  1. import "gorm.io/hints"
  2. DB.Clauses(hints.UseIndex("idx_user_name")).Find(&User{})
  3. // SELECT * FROM `users` USE INDEX (`idx_user_name`)
  4. DB.Clauses(hints.ForceIndex("idx_user_name", "idx_user_id").ForJoin()).Find(&User{})
  5. // SELECT * FROM `users` FORCE INDEX FOR JOIN (`idx_user_name`,`idx_user_id`)"
  6. DB.Clauses(
  7. hints.ForceIndex("idx_user_name", "idx_user_id").ForOrderBy(),
  8. hints.IgnoreIndex("idx_user_name").ForGroupBy(),
  9. ).Find(&User{})
  10. // SELECT * FROM `users` FORCE INDEX FOR ORDER BY (`idx_user_name`,`idx_user_id`) IGNORE INDEX FOR GROUP BY (`idx_user_name`)"

备注提示

  1. import "gorm.io/hints"
  2. DB.Clauses(hints.Comment("select", "master")).Find(&User{})
  3. // SELECT /*master*/ * FROM `users`;
  4. DB.Clauses(hints.CommentBefore("insert", "node2")).Create(&user)
  5. // /*node2*/ INSERT INTO `users` ...;
  6. DB.Clauses(hints.CommentAfter("select", "node2")).Create(&user)
  7. // /*node2*/ INSERT INTO `users` ...;
  8. DB.Clauses(hints.CommentAfter("where", "hint")).Find(&User{}, "id = ?", 1)
  9. // SELECT * FROM `users` WHERE id = ? /* hint */