Skip to content

Commit

Permalink
multiple Cols support (go-xorm#653)
Browse files Browse the repository at this point in the history
  • Loading branch information
lunny authored Jul 24, 2017
1 parent 8cfde0e commit dbc493d
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
32 changes: 32 additions & 0 deletions session_cols_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,35 @@ func TestSetExpr(t *testing.T) {
assert.NoError(t, err)
assert.EqualValues(t, 1, cnt)
}

func TestCols(t *testing.T) {
assert.NoError(t, prepareEngine())

type ColsTable struct {
Id int64
Col1 string
Col2 string
}

assertSync(t, new(ColsTable))

_, err := testEngine.Insert(&ColsTable{
Col1: "1",
Col2: "2",
})
assert.NoError(t, err)

sess := testEngine.ID(1)
_, err = sess.Cols("col1").Cols("col2").Update(&ColsTable{
Col1: "",
Col2: "",
})
assert.NoError(t, err)

var tb ColsTable
has, err := testEngine.ID(1).Get(&tb)
assert.NoError(t, err)
assert.True(t, has)
assert.EqualValues(t, "", tb.Col1)
assert.EqualValues(t, "", tb.Col2)
}
18 changes: 17 additions & 1 deletion statement.go
Original file line number Diff line number Diff line change
Expand Up @@ -592,6 +592,22 @@ func (statement *Statement) col2NewColsWithQuote(columns ...string) []string {
return newColumns
}

func (statement *Statement) colmap2NewColsWithQuote() []string {
newColumns := make([]string, 0, len(statement.columnMap))
for col := range statement.columnMap {
fields := strings.Split(strings.TrimSpace(col), ".")
if len(fields) == 1 {
newColumns = append(newColumns, statement.Engine.quote(fields[0]))
} else if len(fields) == 2 {
newColumns = append(newColumns, statement.Engine.quote(fields[0])+"."+
statement.Engine.quote(fields[1]))
} else {
panic(errors.New("unwanted colnames"))
}
}
return newColumns
}

// Distinct generates "DISTINCT col1, col2 " statement
func (statement *Statement) Distinct(columns ...string) *Statement {
statement.IsDistinct = true
Expand All @@ -618,7 +634,7 @@ func (statement *Statement) Cols(columns ...string) *Statement {
statement.columnMap[strings.ToLower(nc)] = true
}

newColumns := statement.col2NewColsWithQuote(columns...)
newColumns := statement.colmap2NewColsWithQuote()
statement.ColumnStr = strings.Join(newColumns, ", ")
statement.ColumnStr = strings.Replace(statement.ColumnStr, statement.Engine.quote("*"), "*", -1)
return statement
Expand Down

0 comments on commit dbc493d

Please sign in to comment.