add query hint support (#2351)

* add query hint support

* remove add extra space

* add test and fix bug

* fix ut

* fix ut
This commit is contained in:
Dozer 2019-12-06 09:16:51 +08:00 committed by Jinzhu
parent 5490a87fe9
commit 9d2b65f8c9
3 changed files with 34 additions and 0 deletions

View File

@ -60,6 +60,11 @@ func queryCallback(scope *Scope) {
if !scope.HasError() { if !scope.HasError() {
scope.db.RowsAffected = 0 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 { if str, ok := scope.Get("gorm:query_option"); ok {
scope.SQL += addExtraSpaceIfExist(fmt.Sprint(str)) scope.SQL += addExtraSpaceIfExist(fmt.Sprint(str))
} }

View File

@ -23,6 +23,11 @@ type RowsQueryResult struct {
func rowQueryCallback(scope *Scope) { func rowQueryCallback(scope *Scope) {
if result, ok := scope.InstanceGet("row_query_result"); ok { if result, ok := scope.InstanceGet("row_query_result"); ok {
scope.prepareQuerySQL() 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 { if str, ok := scope.Get("gorm:query_option"); ok {
scope.SQL += addExtraSpaceIfExist(fmt.Sprint(str)) scope.SQL += addExtraSpaceIfExist(fmt.Sprint(str))
} }

View File

@ -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) { func TestFloatColumnPrecision(t *testing.T) {
if dialect := os.Getenv("GORM_DIALECT"); dialect != "mysql" && dialect != "sqlite" { if dialect := os.Getenv("GORM_DIALECT"); dialect != "mysql" && dialect != "sqlite" {
t.Skip() t.Skip()