mirror of https://github.com/VinGarcia/ksql.git
Remove the gorm dependency from the Update func
parent
4c740118fd
commit
417ea4660f
53
kiss_orm.go
53
kiss_orm.go
|
@ -4,6 +4,7 @@ import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/jinzhu/gorm"
|
"github.com/jinzhu/gorm"
|
||||||
)
|
)
|
||||||
|
@ -241,20 +242,62 @@ func (c Client) Update(
|
||||||
records ...interface{},
|
records ...interface{},
|
||||||
) error {
|
) error {
|
||||||
for _, record := range records {
|
for _, record := range records {
|
||||||
m, err := StructToMap(record)
|
query, params, err := buildUpdateQuery(c.tableName, record, "id")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
delete(m, "id")
|
|
||||||
r := c.db.Table(c.tableName).Model(record).Updates(m)
|
_, err = c.db.DB().Exec(query, params...)
|
||||||
if r.Error != nil {
|
if err != nil {
|
||||||
return r.Error
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func buildUpdateQuery(
|
||||||
|
tableName string,
|
||||||
|
record interface{},
|
||||||
|
idFieldNames ...string,
|
||||||
|
) (query string, args []interface{}, err error) {
|
||||||
|
recordMap, err := StructToMap(record)
|
||||||
|
if err != nil {
|
||||||
|
return "", nil, err
|
||||||
|
}
|
||||||
|
numAttrs := len(recordMap)
|
||||||
|
numIDs := len(idFieldNames)
|
||||||
|
args = make([]interface{}, numAttrs+numIDs)
|
||||||
|
whereArgs := args[numAttrs-1:]
|
||||||
|
|
||||||
|
var whereQuery []string
|
||||||
|
for i, fieldName := range idFieldNames {
|
||||||
|
whereArgs[i] = recordMap[fieldName]
|
||||||
|
whereQuery = append(whereQuery, fmt.Sprintf("`%s` = ?", fieldName))
|
||||||
|
delete(recordMap, fieldName)
|
||||||
|
}
|
||||||
|
|
||||||
|
keys := []string{}
|
||||||
|
for key := range recordMap {
|
||||||
|
keys = append(keys, key)
|
||||||
|
}
|
||||||
|
|
||||||
|
var setQuery []string
|
||||||
|
for i, k := range keys {
|
||||||
|
args[i] = recordMap[k]
|
||||||
|
setQuery = append(setQuery, fmt.Sprintf("`%s` = ?", k))
|
||||||
|
}
|
||||||
|
|
||||||
|
query = fmt.Sprintf(
|
||||||
|
"UPDATE `%s` SET %s WHERE %s",
|
||||||
|
tableName,
|
||||||
|
strings.Join(setQuery, ", "),
|
||||||
|
strings.Join(whereQuery, ", "),
|
||||||
|
)
|
||||||
|
|
||||||
|
return query, args, nil
|
||||||
|
}
|
||||||
|
|
||||||
// This cache is kept as a pkg variable
|
// This cache is kept as a pkg variable
|
||||||
// because the total number of types on a program
|
// because the total number of types on a program
|
||||||
// should be finite. So keeping a single cache here
|
// should be finite. So keeping a single cache here
|
||||||
|
|
Loading…
Reference in New Issue