Browse Source

Support count with cols (#1595)

Support count with cols

Reviewed-on: #1595
tags/v1.0.0
Lunny Xiao 2 weeks ago
parent
commit
94fd254638
3 changed files with 28 additions and 0 deletions
  1. +1
    -0
      interface.go
  2. +3
    -0
      internal/statements/query.go
  3. +24
    -0
      session_stats_test.go

+ 1
- 0
interface.go 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)


+ 3
- 0
internal/statements/query.go 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(*)"
}


+ 24
- 0
session_stats_test.go 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)
}

Loading…
Cancel
Save