gorm/callbacks/helper.go

86 lines
2.1 KiB
Go
Raw Normal View History

2020-02-19 07:53:46 +03:00
package callbacks
import (
"sort"
2020-06-02 04:16:07 +03:00
"gorm.io/gorm"
"gorm.io/gorm/clause"
2020-02-19 07:53:46 +03:00
)
// ConvertMapToValuesForCreate convert map to values
func ConvertMapToValuesForCreate(stmt *gorm.Statement, mapValue map[string]interface{}) (values clause.Values) {
2020-07-16 06:27:04 +03:00
values.Columns = make([]clause.Column, 0, len(mapValue))
2020-06-30 11:53:54 +03:00
selectColumns, restricted := stmt.SelectAndOmitColumns(true, false)
2020-02-19 07:53:46 +03:00
var keys []string
2020-06-07 10:24:34 +03:00
for k := range mapValue {
2020-02-19 07:53:46 +03:00
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
2020-03-07 08:43:20 +03:00
value := mapValue[k]
2020-08-27 11:27:59 +03:00
if stmt.Schema != nil {
if field := stmt.Schema.LookUpField(k); field != nil {
k = field.DBName
}
2020-02-19 07:53:46 +03:00
}
if v, ok := selectColumns[k]; (ok && v) || (!ok && !restricted) {
2020-07-16 06:27:04 +03:00
values.Columns = append(values.Columns, clause.Column{Name: k})
2020-08-17 12:41:36 +03:00
if len(values.Values) == 0 {
values.Values = [][]interface{}{{}}
}
2020-03-07 08:43:20 +03:00
values.Values[0] = append(values.Values[0], value)
2020-02-19 07:53:46 +03:00
}
}
return
}
// ConvertSliceOfMapToValuesForCreate convert slice of map to values
func ConvertSliceOfMapToValuesForCreate(stmt *gorm.Statement, mapValues []map[string]interface{}) (values clause.Values) {
2020-02-19 07:53:46 +03:00
var (
columns = []string{}
result = map[string][]interface{}{}
2020-06-30 11:53:54 +03:00
selectColumns, restricted = stmt.SelectAndOmitColumns(true, false)
2020-02-19 07:53:46 +03:00
)
for idx, mapValue := range mapValues {
for k, v := range mapValue {
2020-08-27 11:27:59 +03:00
if stmt.Schema != nil {
if field := stmt.Schema.LookUpField(k); field != nil {
k = field.DBName
}
2020-02-19 07:53:46 +03:00
}
if _, ok := result[k]; !ok {
if v, ok := selectColumns[k]; (ok && v) || (!ok && !restricted) {
result[k] = make([]interface{}, len(mapValues))
columns = append(columns, k)
} else {
continue
}
}
result[k][idx] = v
}
}
sort.Strings(columns)
values.Values = make([][]interface{}, len(mapValues))
2020-08-17 12:41:36 +03:00
values.Columns = make([]clause.Column, len(columns))
2020-02-19 07:53:46 +03:00
for idx, column := range columns {
2020-08-17 12:41:36 +03:00
values.Columns[idx] = clause.Column{Name: column}
2020-02-19 07:53:46 +03:00
for i, v := range result[column] {
2020-08-17 12:41:36 +03:00
if len(values.Values[i]) == 0 {
2020-02-19 07:53:46 +03:00
values.Values[i] = make([]interface{}, len(columns))
}
2020-08-17 12:41:36 +03:00
2020-02-19 07:53:46 +03:00
values.Values[i][idx] = v
}
}
return
}