gorm/clause/set.go

61 lines
1.4 KiB
Go
Raw Permalink 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 {
2021-11-29 06:02:32 +03:00
builder.WriteQuoted(Column{Name: PrimaryKey})
2020-02-07 18:45:35 +03:00
builder.WriteByte('=')
2021-11-29 06:02:32 +03:00
builder.WriteQuoted(Column{Name: PrimaryKey})
2020-02-07 18:45:35 +03:00
}
}
// 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 {
2020-06-08 08:45:41 +03:00
keys := make([]string, 0, len(values))
2020-06-06 12:47:30 +03:00
for key := range values {
keys = append(keys, key)
}
sort.Strings(keys)
2020-06-08 08:45:41 +03:00
assignments := make([]Assignment, len(keys))
for idx, key := range keys {
assignments[idx] = Assignment{Column: Column{Name: key}, Value: values[key]}
2020-06-06 12:47:30 +03:00
}
return assignments
}
2020-06-09 04:04:25 +03:00
func AssignmentColumns(values []string) Set {
assignments := make([]Assignment, len(values))
for idx, value := range values {
assignments[idx] = Assignment{Column: Column{Name: value}, Value: Column{Table: "excluded", Name: value}}
}
return assignments
}