GORM provides optimizer/index/comment hints support

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

Optimizer Hints

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

Index Hints

  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`)"

Comment Hints

  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 */