From b5de8aeb425cc9eccf92b8c3252fc0a7201ed52e Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 18 Aug 2020 18:58:53 +0800 Subject: [PATCH] Fix overrite SELECT clause --- chainable_api.go | 3 +++ finisher_api.go | 2 +- tests/query_test.go | 5 +++++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/chainable_api.go b/chainable_api.go index 4df8780e..78724cc8 100644 --- a/chainable_api.go +++ b/chainable_api.go @@ -91,6 +91,7 @@ func (db *DB) Select(query interface{}, args ...interface{}) (tx *DB) { return } } + delete(tx.Statement.Clauses, "SELECT") case string: fields := strings.FieldsFunc(v, utils.IsChar) @@ -112,6 +113,8 @@ func (db *DB) Select(query interface{}, args ...interface{}) (tx *DB) { return } } + + delete(tx.Statement.Clauses, "SELECT") } else { tx.Statement.AddClause(clause.Select{ Distinct: db.Statement.Distinct, diff --git a/finisher_api.go b/finisher_api.go index 19534460..88873948 100644 --- a/finisher_api.go +++ b/finisher_api.go @@ -294,7 +294,7 @@ func (db *DB) Count(count *int64) (tx *DB) { if len(tx.Statement.Selects) == 0 { tx.Statement.AddClause(clause.Select{Expression: clause.Expr{SQL: "count(1)"}}) - defer tx.Statement.AddClause(clause.Select{}) + defer delete(tx.Statement.Clauses, "SELECT") } else if !strings.Contains(strings.ToLower(tx.Statement.Selects[0]), "count(") { expr := clause.Expr{SQL: "count(1)"} diff --git a/tests/query_test.go b/tests/query_test.go index 72dd89b9..d71c813a 100644 --- a/tests/query_test.go +++ b/tests/query_test.go @@ -346,6 +346,11 @@ func TestSelect(t *testing.T) { if !regexp.MustCompile(`SELECT u\.\* FROM .*users.*`).MatchString(r.Statement.SQL.String()) { t.Fatalf("Build Select with u.*, but got %v", r.Statement.SQL.String()) } + + r = dryDB.Select("count(*)").Select("u.*").Table("users as u").First(&User{}, user.ID) + if !regexp.MustCompile(`SELECT u\.\* FROM .*users.*`).MatchString(r.Statement.SQL.String()) { + t.Fatalf("Build Select with u.*, but got %v", r.Statement.SQL.String()) + } } func TestOmit(t *testing.T) {