diff --git a/main.go b/main.go index 17c75ed3..d547fc45 100644 --- a/main.go +++ b/main.go @@ -191,6 +191,11 @@ func (s *DB) SubQuery() *expr { 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 func (s *DB) Where(query interface{}, args ...interface{}) *DB { return s.clone().search.Where(query, args...).db diff --git a/scope.go b/scope.go index 378025bd..26698578 100644 --- a/scope.go +++ b/scope.go @@ -708,6 +708,10 @@ func (scope *Scope) buildSelectQuery(clause map[string]interface{}) (str string) return } +func (scope *Scope) useIndexSQL() string { + return fmt.Sprintf("USE INDEX(%s)", scope.Search.useIndex) +} + func (scope *Scope) whereSQL() (sql string) { var ( quotedTableName = scope.QuotedTableName() diff --git a/scope_test.go b/scope_test.go index 3018f350..b341fc30 100644 --- a/scope_test.go +++ b/scope_test.go @@ -10,7 +10,7 @@ import ( ) 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 { diff --git a/search.go b/search.go index 90138595..288c4dcb 100644 --- a/search.go +++ b/search.go @@ -21,6 +21,7 @@ type search struct { limit interface{} group string tableName string + useIndex string raw bool Unscoped bool ignoreOrderQuery bool @@ -36,6 +37,15 @@ func (s *search) clone() *search { 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 { s.whereConditions = append(s.whereConditions, map[string]interface{}{"query": query, "args": values}) return s