gorm/clause/order_by.go

55 lines
1.1 KiB
Go
Raw Permalink 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 {
2020-11-03 05:30:05 +03:00
Columns []OrderByColumn
Expression Expression
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) {
2020-11-03 05:30:05 +03:00
if orderBy.Expression != nil {
orderBy.Expression.Build(builder)
} else {
for idx, column := range orderBy.Columns {
if idx > 0 {
builder.WriteByte(',')
}
2020-02-04 03:56:15 +03:00
2020-11-03 05:30:05 +03:00
builder.WriteQuoted(column.Column)
if column.Desc {
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
}