diff --git a/session.go b/session.go index 8d611255..aa3aec73 100644 --- a/session.go +++ b/session.go @@ -219,12 +219,7 @@ func (session *Session) OrderBy(order string) *Session { // Method Desc provide desc order by query condition, the input parameters are columns. func (session *Session) Desc(colNames ...string) *Session { - if session.Statement.OrderStr != "" { - session.Statement.OrderStr += ", " - } - newColNames := col2NewCols(colNames...) - sqlStr := strings.Join(newColNames, session.Engine.Quote(" DESC, ")) - session.Statement.OrderStr += session.Engine.Quote(sqlStr) + " DESC" + session.Statement.Desc(colNames...) return session } diff --git a/statement.go b/statement.go index 74daf9fb..332f87cb 100644 --- a/statement.go +++ b/statement.go @@ -2,6 +2,7 @@ package xorm import ( "encoding/json" + "errors" "fmt" "reflect" "strings" @@ -771,6 +772,27 @@ func col2NewCols(columns ...string) []string { return newColumns } +func (statement *Statement) col2NewColsWithQuote(columns ...string) []string { + newColumns := make([]string, 0) + for _, col := range columns { + strings.Replace(col, "`", "", -1) + strings.Replace(col, statement.Engine.QuoteStr(), "", -1) + ccols := strings.Split(col, ",") + for _, c := range ccols { + fields := strings.Split(strings.TrimSpace(c), ".") + 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 +} + // Generate "Distince col1, col2 " statment func (statement *Statement) Distinct(columns ...string) *Statement { statement.IsDistinct = true @@ -851,10 +873,34 @@ func (statement *Statement) Limit(limit int, start ...int) *Statement { // Generate "Order By order" statement func (statement *Statement) OrderBy(order string) *Statement { + if statement.OrderStr != "" { + statement.OrderStr += ", " + } statement.OrderStr = order return statement } +func (statement *Statement) Desc(colNames ...string) *Statement { + if statement.OrderStr != "" { + statement.OrderStr += ", " + } + newColNames := statement.col2NewColsWithQuote(colNames...) + sqlStr := strings.Join(newColNames, " DESC, ") + statement.OrderStr += sqlStr + " DESC" + return statement +} + +// Method Asc provide asc order by query condition, the input parameters are columns. +func (statement *Statement) Asc(colNames ...string) *Statement { + if statement.OrderStr != "" { + statement.OrderStr += ", " + } + newColNames := statement.col2NewColsWithQuote(colNames...) + sqlStr := strings.Join(newColNames, " ASC, ") + statement.OrderStr += sqlStr + " ASC" + return statement +} + //The join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN func (statement *Statement) Join(join_operator, tablename, condition string) *Statement { if statement.JoinStr != "" {