gorm/clause/set.go

58 lines
1.1 KiB
Go
Raw Normal View History

2020-02-07 18:45:35 +03:00
package clause
2020-06-06 12:47:30 +03:00
import "sort"
2020-02-07 18:45:35 +03:00
type Set []Assignment
type Assignment struct {
Column Column
Value interface{}
}
func (set Set) Name() string {
return "SET"
}
func (set Set) Build(builder Builder) {
if len(set) > 0 {
for idx, assignment := range set {
if idx > 0 {
builder.WriteByte(',')
}
builder.WriteQuoted(assignment.Column)
builder.WriteByte('=')
2020-03-09 12:07:00 +03:00
builder.AddVar(builder, assignment.Value)
2020-02-07 18:45:35 +03:00
}
} else {
builder.WriteQuoted(PrimaryColumn)
builder.WriteByte('=')
builder.WriteQuoted(PrimaryColumn)
}
}
// MergeClause merge assignments clauses
func (set Set) MergeClause(clause *Clause) {
copiedAssignments := make([]Assignment, len(set))
copy(copiedAssignments, set)
clause.Expression = Set(copiedAssignments)
2020-02-07 18:45:35 +03:00
}
2020-06-06 12:47:30 +03:00
func Assignments(values map[string]interface{}) Set {
var keys []string
var assignments []Assignment
for key := range values {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
assignments = append(assignments, Assignment{
2020-06-07 04:39:39 +03:00
Column: Column{Name: key},
2020-06-06 12:47:30 +03:00
Value: values[key],
})
}
return assignments
}