Support count with cols #1595

Merged
lunny merged 1 commits from lunny/fix_count into master 2020-03-11 03:29:47 +00:00
3 changed files with 28 additions and 0 deletions

View File

@ -59,6 +59,7 @@ type Interface interface {
QueryString(sqlOrArgs ...interface{}) ([]map[string]string, error)
Rows(bean interface{}) (*Rows, error)
SetExpr(string, interface{}) *Session
Select(string) *Session
SQL(interface{}, ...interface{}) *Session
Sum(bean interface{}, colName string) (float64, error)
SumInt(bean interface{}, colName string) (int64, error)

View File

@ -153,6 +153,7 @@ func (statement *Statement) GenGetSQL(bean interface{}) (string, []interface{},
return sqlStr, append(statement.joinArgs, condArgs...), nil
}
// GenCountSQL generates the SQL for counting
func (statement *Statement) GenCountSQL(beans ...interface{}) (string, []interface{}, error) {
if statement.RawSQL != "" {
return statement.GenRawSQL(), statement.RawParams, nil
@ -171,6 +172,8 @@ func (statement *Statement) GenCountSQL(beans ...interface{}) (string, []interfa
if len(selectSQL) <= 0 {
if statement.IsDistinct {
selectSQL = fmt.Sprintf("count(DISTINCT %s)", statement.ColumnStr())
} else if statement.ColumnStr() != "" {
selectSQL = fmt.Sprintf("count(%s)", statement.ColumnStr())
} else {
selectSQL = "count(*)"
}

View File

@ -274,3 +274,27 @@ func TestWithTableName(t *testing.T) {
assert.NoError(t, err)
assert.EqualValues(t, 2, total)
}
func TestCountWithSelectCols(t *testing.T) {
assert.NoError(t, prepareEngine())
assertSync(t, new(CountWithTableName))
_, err := testEngine.Insert(&CountWithTableName{
Name: "orderby",
})
assert.NoError(t, err)
_, err = testEngine.Insert(CountWithTableName{
Name: "limit",
})
assert.NoError(t, err)
total, err := testEngine.Cols("id").Count(new(CountWithTableName))
assert.NoError(t, err)
assert.EqualValues(t, 2, total)
total, err = testEngine.Select("count(id)").Count(CountWithTableName{})
assert.NoError(t, err)
assert.EqualValues(t, 2, total)
}