From 0f339654dd9ac3e3e41c49dc0095ee6ac3320ad9 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 4 May 2018 13:09:54 +0800 Subject: [PATCH] fix cols and distinct conflicts (#927) --- session_cols.go | 8 ++++++++ statement.go | 2 +- statement_test.go | 23 +++++++++++++++++++++++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/session_cols.go b/session_cols.go index 1c2b023d8..47d109c6c 100644 --- a/session_cols.go +++ b/session_cols.go @@ -47,6 +47,14 @@ func (m columnMap) contain(colName string) bool { return false } +func (m *columnMap) add(colName string) bool { + if m.contain(colName) { + return false + } + *m = append(*m, colName) + return true +} + func setColumnInt(bean interface{}, col *core.Column, t int64) { v, err := col.ValueOf(bean) if err != nil { diff --git a/statement.go b/statement.go index 38fa26d2e..c67d8c01c 100644 --- a/statement.go +++ b/statement.go @@ -624,7 +624,7 @@ func (statement *Statement) Select(str string) *Statement { func (statement *Statement) Cols(columns ...string) *Statement { cols := col2NewCols(columns...) for _, nc := range cols { - statement.columnMap = append(statement.columnMap, nc) + statement.columnMap.add(nc) } newColumns := statement.colmap2NewColsWithQuote() diff --git a/statement_test.go b/statement_test.go index 758c2759d..8a7667f5f 100644 --- a/statement_test.go +++ b/statement_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/go-xorm/core" + "github.com/stretchr/testify/assert" ) var colStrTests = []struct { @@ -180,3 +181,25 @@ func createTestStatement() *Statement { } return nil } + +func TestDistinctAndCols(t *testing.T) { + type DistinctAndCols struct { + Id int64 + Name string + } + + assert.NoError(t, prepareEngine()) + assertSync(t, new(DistinctAndCols)) + + cnt, err := testEngine.Insert(&DistinctAndCols{ + Name: "test", + }) + assert.NoError(t, err) + assert.EqualValues(t, 1, cnt) + + var names []string + err = testEngine.Table("distinct_and_cols").Cols("name").Distinct("name").Find(&names) + assert.NoError(t, err) + assert.EqualValues(t, 1, len(names)) + assert.EqualValues(t, "test", names[0]) +}