Skip to content
Open
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
2 changes: 2 additions & 0 deletions finisher_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,8 @@ func (db *DB) Count(count *int64) (tx *DB) {
}

tx.Statement.AddClause(clause.Select{Expression: expr})
} else if strings.HasPrefix(strings.TrimSpace(strings.ToLower(tx.Statement.Selects[0])), "count(") {
tx.Statement.AddClause(clause.Select{Expression: clause.Expr{SQL: tx.Statement.Selects[0]}})
}

if orderByClause, ok := db.Statement.Clauses["ORDER BY"]; ok {
Expand Down
10 changes: 10 additions & 0 deletions tests/count_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,16 @@ func TestCount(t *testing.T) {
t.Fatalf("Build count with select, but got %v", result.Statement.SQL.String())
}

result = dryDB.Model(&User{}).Distinct("name").Joins("Team").Count(&count)
if !regexp.MustCompile(`SELECT COUNT\(DISTINCT\(.name.\)\) FROM .*users.* JOIN .*users.*`).MatchString(result.Statement.SQL.String()) {
t.Fatalf("Build count with select, but got %v", result.Statement.SQL.String())
}

result = dryDB.Model(&User{}).Select("COUNT(DISTINCT(`name`))").Joins("Team").Count(&count)
if !regexp.MustCompile(`SELECT COUNT\(DISTINCT\(.name.\)\) FROM .*users.* JOIN .*users.*`).MatchString(result.Statement.SQL.String()) {
t.Fatalf("Build count with select, but got %v", result.Statement.SQL.String())
}

var count4 int64
if err := DB.Table("users").Joins("LEFT JOIN companies on companies.name = users.name").Where("users.name = ?", user1.Name).Count(&count4).Error; err != nil || count4 != 1 {
t.Errorf("count with join, got error: %v, count %v", err, count4)
Expand Down
Loading