improve raw sql count statement for package gdb

This commit is contained in:
John Guo
2021-06-21 19:21:38 +08:00
parent 7c8bbcb3af
commit 266f592739
2 changed files with 17 additions and 0 deletions

View File

@ -515,6 +515,11 @@ func (m *Model) getFormattedSqlAndArgs(queryType int, limit1 bool) (sqlWithHolde
// DISTINCT t.user_id uid
countFields = fmt.Sprintf(`COUNT(%s%s)`, m.distinct, m.fields)
}
// Raw SQL Model.
if m.rawSql != "" {
sqlWithHolder = fmt.Sprintf("SELECT %s FROM (%s) AS T", countFields, m.rawSql)
return sqlWithHolder, nil
}
conditionWhere, conditionExtra, conditionArgs := m.formatCondition(false, true)
sqlWithHolder = fmt.Sprintf("SELECT %s FROM %s%s", countFields, m.tables, conditionWhere+conditionExtra)
if len(m.groupBy) > 0 {

View File

@ -3714,4 +3714,16 @@ func Test_Model_Raw(t *testing.T) {
t.Assert(all[0]["id"], 7)
t.Assert(all[1]["id"], 5)
})
gtest.C(t, func(t *gtest.T) {
count, err := db.
Raw(fmt.Sprintf("select * from %s where id in (?)", table), g.Slice{1, 5, 7, 8, 9, 10}).
WhereLT("id", 8).
WhereIn("id", g.Slice{1, 2, 3, 4, 5, 6, 7}).
OrderDesc("id").
Limit(2).
Count()
t.AssertNil(err)
t.Assert(count, 6)
})
}