
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.
43 lines
972 B
Go
43 lines
972 B
Go
package clause
|
|
|
|
// GroupBy group by clause
|
|
type GroupBy struct {
|
|
Columns []Column
|
|
Having []Expression
|
|
}
|
|
|
|
// Name from clause name
|
|
func (groupBy GroupBy) Name() string {
|
|
return "GROUP BY"
|
|
}
|
|
|
|
// Build build group by clause
|
|
func (groupBy GroupBy) Build(builder Builder) {
|
|
for idx, column := range groupBy.Columns {
|
|
if idx > 0 {
|
|
builder.WriteByte(',')
|
|
}
|
|
|
|
builder.WriteQuoted(column)
|
|
}
|
|
|
|
if len(groupBy.Having) > 0 {
|
|
builder.WriteString(" HAVING ")
|
|
Where{Exprs: groupBy.Having}.Build(builder)
|
|
}
|
|
}
|
|
|
|
// MergeClause merge group by clause
|
|
func (groupBy GroupBy) MergeClause(clause *Clause) {
|
|
if v, ok := clause.Expression.(GroupBy); ok {
|
|
copiedColumns := make([]Column, len(v.Columns))
|
|
copy(copiedColumns, v.Columns)
|
|
groupBy.Columns = append(copiedColumns, groupBy.Columns...)
|
|
|
|
copiedHaving := make([]Expression, len(v.Having))
|
|
copy(copiedHaving, v.Having)
|
|
groupBy.Having = append(copiedHaving, groupBy.Having...)
|
|
}
|
|
clause.Expression = groupBy
|
|
}
|