fusenapi/utils/fssql/metadata.go

92 lines
2.0 KiB
Go
Raw Normal View History

2023-09-08 10:56:17 +00:00
package fssql
import (
"encoding/json"
"fmt"
"reflect"
"gorm.io/gorm"
)
// func MetadataPATCH(tx *gorm.DB, module string, tableStructPointer any, updateMetadata any, rawID int64) error {
// stype := reflect.TypeOf(tableStructPointer)
// if stype.Kind() == reflect.Pointer {
// stype = stype.Elem()
// }
// updatesql := `UPDATE %s
// SET metadata = CASE
// WHEN metadata IS NULL THEN ?
// ELSE JSON_MERGE_PATCH(metadata, ?)
// END
// WHERE module = '%s' and id = ?;`
// var err error
// var metadata []byte
// switch mdata := updateMetadata.(type) {
// case []byte:
// metadata = mdata
// case string:
// metadata = []byte(mdata)
// default:
// metadata, err = json.Marshal(updateMetadata)
// if err != nil {
// return err
// }
// }
// updatesql = fmt.Sprintf(updatesql, tx.NamingStrategy.TableName(stype.Name()), module)
// logx.Error(updatesql)
// err = tx.Exec(updatesql, metadata, metadata, rawID).Error
// if err != nil {
// return err
// }
// return nil
// }
2023-09-08 11:01:29 +00:00
// tableStructPointer 表结构 updateMetadata 可以是json的[]byte也可以结构体
2023-09-08 10:56:17 +00:00
func MetadataPATCH(tx *gorm.DB, module string, tableStructPointer any, updateMetadata any, WhereKeysCond string, value ...any) error {
stype := reflect.TypeOf(tableStructPointer)
if stype.Kind() == reflect.Pointer {
stype = stype.Elem()
}
updatesql := `UPDATE %s
SET metadata = CASE
WHEN metadata IS NULL THEN ?
ELSE JSON_MERGE_PATCH(metadata, ?)
END
WHERE module = '%s' and %s;`
var err error
var metadata []byte
switch mdata := updateMetadata.(type) {
case []byte:
metadata = mdata
case string:
metadata = []byte(mdata)
default:
metadata, err = json.Marshal(updateMetadata)
if err != nil {
return err
}
}
var values []any
values = append(values, metadata, metadata)
values = append(values, value...)
updatesql = fmt.Sprintf(updatesql, tx.NamingStrategy.TableName(stype.Name()), module, WhereKeysCond)
2023-09-08 11:02:37 +00:00
// logx.Error(updatesql)
2023-09-08 10:56:17 +00:00
err = tx.Exec(updatesql, values).Error
if err != nil {
return err
}
return nil
}