add UseIndex API

This commit is contained in:
Yu Changhong 2018-09-28 22:56:28 +08:00
parent f6260a0085
commit f62781cad0
4 changed files with 20 additions and 1 deletions

View File

@ -191,6 +191,11 @@ func (s *DB) SubQuery() *expr {
return Expr(fmt.Sprintf("(%v)", scope.SQL), scope.SQLVars...) return Expr(fmt.Sprintf("(%v)", scope.SQL), scope.SQLVars...)
} }
// UseIndex use a specified index when query
func (s *DB) UseIndex(index string) *DB {
return s.clone().search.UseIndex(index).db
}
// Where return a new relation, filter records with given conditions, accepts `map`, `struct` or `string` as conditions, refer http://jinzhu.github.io/gorm/crud.html#query // Where return a new relation, filter records with given conditions, accepts `map`, `struct` or `string` as conditions, refer http://jinzhu.github.io/gorm/crud.html#query
func (s *DB) Where(query interface{}, args ...interface{}) *DB { func (s *DB) Where(query interface{}, args ...interface{}) *DB {
return s.clone().search.Where(query, args...).db return s.clone().search.Where(query, args...).db

View File

@ -708,6 +708,10 @@ func (scope *Scope) buildSelectQuery(clause map[string]interface{}) (str string)
return return
} }
func (scope *Scope) useIndexSQL() string {
return fmt.Sprintf("USE INDEX(%s)", scope.Search.useIndex)
}
func (scope *Scope) whereSQL() (sql string) { func (scope *Scope) whereSQL() (sql string) {
var ( var (
quotedTableName = scope.QuotedTableName() quotedTableName = scope.QuotedTableName()

View File

@ -10,7 +10,7 @@ import (
) )
func NameIn1And2(d *gorm.DB) *gorm.DB { func NameIn1And2(d *gorm.DB) *gorm.DB {
return d.Where("name in (?)", []string{"ScopeUser1", "ScopeUser2"}) return d.UseIndex("PRIMARY").Where("name in (?)", []string{"ScopeUser1", "ScopeUser2"})
} }
func NameIn2And3(d *gorm.DB) *gorm.DB { func NameIn2And3(d *gorm.DB) *gorm.DB {

View File

@ -21,6 +21,7 @@ type search struct {
limit interface{} limit interface{}
group string group string
tableName string tableName string
useIndex string
raw bool raw bool
Unscoped bool Unscoped bool
ignoreOrderQuery bool ignoreOrderQuery bool
@ -36,6 +37,15 @@ func (s *search) clone() *search {
return &clone return &clone
} }
// UseIndex makes SQL use the specified index
//
// SELECT * FROM trades USE INDEX(index_trades_on_market_uuid) WHERE market_uuid="test market" ORDER BY id DESC;
//
func (s *search) UseIndex(index string) *search {
s.useIndex = index
return s
}
func (s *search) Where(query interface{}, values ...interface{}) *search { func (s *search) Where(query interface{}, values ...interface{}) *search {
s.whereConditions = append(s.whereConditions, map[string]interface{}{"query": query, "args": values}) s.whereConditions = append(s.whereConditions, map[string]interface{}{"query": query, "args": values})
return s return s