Skip to content

Commit

Permalink
add query hint support (go-gorm#2351)
Browse files Browse the repository at this point in the history
* add query hint support

* remove add extra space

* add test and fix bug

* fix ut

* fix ut
  • Loading branch information
Dozer authored and jinzhu committed Dec 6, 2019
1 parent 5490a87 commit 9d2b65f
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
5 changes: 5 additions & 0 deletions callback_query.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ func queryCallback(scope *Scope) {

if !scope.HasError() {
scope.db.RowsAffected = 0

if str, ok := scope.Get("gorm:query_hint"); ok {
scope.SQL = fmt.Sprint(str) + scope.SQL
}

if str, ok := scope.Get("gorm:query_option"); ok {
scope.SQL += addExtraSpaceIfExist(fmt.Sprint(str))
}
Expand Down
5 changes: 5 additions & 0 deletions callback_row_query.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ type RowsQueryResult struct {
func rowQueryCallback(scope *Scope) {
if result, ok := scope.InstanceGet("row_query_result"); ok {
scope.prepareQuerySQL()

if str, ok := scope.Get("gorm:query_hint"); ok {
scope.SQL = fmt.Sprint(str) + scope.SQL
}

if str, ok := scope.Get("gorm:query_option"); ok {
scope.SQL += addExtraSpaceIfExist(fmt.Sprint(str))
}
Expand Down
24 changes: 24 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1333,6 +1333,30 @@ func TestCountWithQueryOption(t *testing.T) {
}
}

func TestQueryHint1(t *testing.T) {
db := DB.New()

_, err := db.Model(User{}).Raw("select 1").Rows()

if err != nil {
t.Error("Unexpected error on query count with query_option")
}
}

func TestQueryHint2(t *testing.T) {
type TestStruct struct {
ID string `gorm:"primary_key"`
Name string
}
DB.DropTable(&TestStruct{})
DB.AutoMigrate(&TestStruct{})

data := TestStruct{ID: "uuid", Name: "hello"}
if err := DB.Set("gorm:query_hint", "/*master*/").Save(&data).Error; err != nil {
t.Error("Unexpected error on query count with query_option")
}
}

func TestFloatColumnPrecision(t *testing.T) {
if dialect := os.Getenv("GORM_DIALECT"); dialect != "mysql" && dialect != "sqlite" {
t.Skip()
Expand Down

0 comments on commit 9d2b65f

Please sign in to comment.