92 lines
2.0 KiB
Go
92 lines
2.0 KiB
Go
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
|
|
// }
|
|
|
|
// tableStructPointer 表结构 updateMetadata 可以是json的[]byte也可以结构体
|
|
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)
|
|
// logx.Error(updatesql)
|
|
err = tx.Exec(updatesql, values).Error
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|