github.com/systematiccaos/gorm@v1.22.6/clause/order_by.go (about)

     1  package clause
     2  
     3  type OrderByColumn struct {
     4  	Column  Column
     5  	Desc    bool
     6  	Reorder bool
     7  }
     8  
     9  type OrderBy struct {
    10  	Columns    []OrderByColumn
    11  	Expression Expression
    12  }
    13  
    14  // Name where clause name
    15  func (orderBy OrderBy) Name() string {
    16  	return "ORDER BY"
    17  }
    18  
    19  // Build build where clause
    20  func (orderBy OrderBy) Build(builder Builder) {
    21  	if orderBy.Expression != nil {
    22  		orderBy.Expression.Build(builder)
    23  	} else {
    24  		for idx, column := range orderBy.Columns {
    25  			if idx > 0 {
    26  				builder.WriteByte(',')
    27  			}
    28  
    29  			builder.WriteQuoted(column.Column)
    30  			if column.Desc {
    31  				builder.WriteString(" DESC")
    32  			}
    33  		}
    34  	}
    35  }
    36  
    37  // MergeClause merge order by clauses
    38  func (orderBy OrderBy) MergeClause(clause *Clause) {
    39  	if v, ok := clause.Expression.(OrderBy); ok {
    40  		for i := len(orderBy.Columns) - 1; i >= 0; i-- {
    41  			if orderBy.Columns[i].Reorder {
    42  				orderBy.Columns = orderBy.Columns[i:]
    43  				clause.Expression = orderBy
    44  				return
    45  			}
    46  		}
    47  
    48  		copiedColumns := make([]OrderByColumn, len(v.Columns))
    49  		copy(copiedColumns, v.Columns)
    50  		orderBy.Columns = append(copiedColumns, orderBy.Columns...)
    51  	}
    52  
    53  	clause.Expression = orderBy
    54  }