gorm/clause/order_by.go

50 lines
998 B
Go
Raw Normal View History

2020-02-02 09:40:44 +03:00
package clause
2020-02-07 18:45:35 +03:00
type OrderByColumn struct {
2020-02-04 03:56:15 +03:00
Column Column
Desc bool
Reorder bool
}
2020-02-07 18:45:35 +03:00
type OrderBy struct {
Columns []OrderByColumn
2020-02-04 03:56:15 +03:00
}
// Name where clause name
2020-02-07 18:45:35 +03:00
func (orderBy OrderBy) Name() string {
2020-02-04 03:56:15 +03:00
return "ORDER BY"
}
// Build build where clause
2020-02-07 18:45:35 +03:00
func (orderBy OrderBy) Build(builder Builder) {
for idx, column := range orderBy.Columns {
if idx > 0 {
builder.WriteByte(',')
2020-02-04 03:56:15 +03:00
}
2020-02-07 18:45:35 +03:00
builder.WriteQuoted(column.Column)
if column.Desc {
2020-03-09 12:07:00 +03:00
builder.WriteString(" DESC")
2020-02-04 03:56:15 +03:00
}
}
}
2020-02-07 18:45:35 +03:00
// MergeClause merge order by clauses
func (orderBy OrderBy) MergeClause(clause *Clause) {
if v, ok := clause.Expression.(OrderBy); ok {
for i := len(orderBy.Columns) - 1; i >= 0; i-- {
if orderBy.Columns[i].Reorder {
orderBy.Columns = orderBy.Columns[i:]
clause.Expression = orderBy
return
}
}
copiedColumns := make([]OrderByColumn, len(v.Columns))
copy(copiedColumns, v.Columns)
orderBy.Columns = append(copiedColumns, orderBy.Columns...)
2020-02-04 03:56:15 +03:00
}
2020-02-07 18:45:35 +03:00
clause.Expression = orderBy
2020-02-02 09:40:44 +03:00
}