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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
Fix Statement Where clone array corruption in v2
Method-chaining in gorm is predicated on a `Clause`'s `MergeClause`
method ensuring that the two clauses are disconnected in terms of
pointers (at least in the Wherec case).
However, the original Where implementation used `append`, which
only returns a new instance if the backing array needs to be resized.
In some cases, this is true. Practically, go doubles the size of the
slice once it gets full, so the following slice `append` calls would
result in a new slice:
* 0 -> 1
* 1 -> 2
* 2 -> 4
* 4 -> 8
* and so on.
So, when the number of "where" conditions was 0, 1, 2, or 4, method-chaining
would work as expected. However, when it was 3, 5, 6, or 7, modifying the
copy would modify the original.
This also updates the "order by", "group by" and "set" clauses.
2020-06-07 23:41:54 +03:00
|
|
|
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
|
|
|
}
|