From df24821896fb65619c892241ecd00ac3e1acd789 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 9 Feb 2021 17:05:50 +0800 Subject: [PATCH] Fix SubQuery for raw sql --- statement.go | 6 ++++++ tests/query_test.go | 11 ++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/statement.go b/statement.go index de1b300f..6ea8c883 100644 --- a/statement.go +++ b/statement.go @@ -438,6 +438,12 @@ func (stmt *Statement) clone() *Statement { SkipHooks: stmt.SkipHooks, } + if stmt.SQL.Len() > 0 { + newStmt.SQL.WriteString(stmt.SQL.String()) + newStmt.Vars = make([]interface{}, 0, len(stmt.Vars)) + newStmt.Vars = append(newStmt.Vars, stmt.Vars...) + } + for k, c := range stmt.Clauses { newStmt.Clauses[k] = c } diff --git a/tests/query_test.go b/tests/query_test.go index c6c7acb0..8ed02c98 100644 --- a/tests/query_test.go +++ b/tests/query_test.go @@ -991,7 +991,16 @@ func TestSubQueryWithRaw(t *testing.T) { DB.Create(&users) var count int64 - err := DB.Raw("select count(*) from (?) tmp", + err := DB.Raw("select count(*) from (?) tmp", DB.Raw("select name from users where age >= ? and name in (?)", 10, []string{"subquery_raw_1", "subquery_raw_3"})).Scan(&count).Error + if err != nil { + t.Errorf("Expected to get no errors, but got %v", err) + } + + if count != 2 { + t.Errorf("Row count must be 1, instead got %d", count) + } + + err = DB.Raw("select count(*) from (?) tmp", DB.Table("users"). Select("name"). Where("age >= ? and name in (?)", 20, []string{"subquery_raw_1", "subquery_raw_3"}).