Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add query hint support #2351

Merged
merged 7 commits into from
Dec 6, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -1262,6 +1262,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