Skip to content

Commit e651891

Browse files
committed
orm支持distinct
1 parent 01d7870 commit e651891

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

orm/orm.go

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,11 +178,25 @@ func (s *Stmt) SQLColumn(rt reflect.Type, table string) string {
178178
case reflect.Slice:
179179
continue
180180
}
181+
182+
attr := ""
181183
name := f.Tag.Get("db")
184+
185+
if kv := strings.Split(name, ","); len(kv) == 2 {
186+
name = kv[0]
187+
attr = kv[1]
188+
}
189+
182190
if name == "" {
183191
name = str.FieldEscape(f.Name)
184192
}
185-
if !strings.Contains(name, ".") {
193+
194+
switch attr {
195+
case "distinct":
196+
bs.WriteString("distinct ")
197+
}
198+
199+
if !strings.Contains(name, ".") && !strings.Contains(name, "(") {
186200
fmt.Fprintf(bs, "%s.", table)
187201
}
188202
fmt.Fprintf(bs, "%s, ", name)

orm/orm_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,24 @@ import (
1010
"gopkg.in/DATA-DOG/go-sqlmock.v1"
1111
)
1212

13+
func TestORMStructDistinct(t *testing.T) {
14+
expect := "select userinfo.id, distinct userinfo.user, avg(age), sum(size), userinfo.password from userinfo limit 1"
15+
result := struct {
16+
ID int64
17+
User string `db:"user,distinct"`
18+
Age int `db:"avg(age)"`
19+
Size int `db:"sum(size)"`
20+
Password string
21+
}{}
22+
sql, err := NewStmt(nil, "userinfo").SQLQueryBuilder(&result)
23+
if err != nil {
24+
t.Fatal(err.Error())
25+
}
26+
if sql != expect {
27+
t.Fatalf("expect:%s,\n recv:%s.", expect, sql)
28+
}
29+
}
30+
1331
func TestORMStruct(t *testing.T) {
1432
expect := "select userinfo.id, userinfo.user, userinfo.password from userinfo limit 1"
1533
result := struct {

0 commit comments

Comments
 (0)