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
|
|
|
)
|
|
|
|
|
2020-04-08 03:15:00 +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-02-19 07:53:46 +03:00
|
|
|
if field := stmt.Schema.LookUpField(k); field != nil {
|
|
|
|
k = field.DBName
|
|
|
|
}
|
|
|
|
|
|
|
|
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-03-07 08:43:20 +03:00
|
|
|
values.Values[0] = append(values.Values[0], value)
|
2020-02-19 07:53:46 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-04-08 03:15:00 +03:00
|
|
|
// 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 {
|
|
|
|
if field := stmt.Schema.LookUpField(k); field != nil {
|
|
|
|
k = field.DBName
|
|
|
|
}
|
|
|
|
|
|
|
|
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))
|
|
|
|
for idx, column := range columns {
|
|
|
|
for i, v := range result[column] {
|
|
|
|
if i == 0 {
|
|
|
|
values.Values[i] = make([]interface{}, len(columns))
|
|
|
|
}
|
|
|
|
values.Values[i][idx] = v
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|