|
@@ -373,6 +373,96 @@ func UpdateEntity(executor Executor, tableName string, e any) error {
|
|
|
return nil
|
|
|
}
|
|
|
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+func UpdateEntityWithRowsAffected(executor Executor, tableName string, e any) (int64, error) {
|
|
|
+ if executor == nil {
|
|
|
+ return 0, errors.New("没有传递执行器")
|
|
|
+ }
|
|
|
+
|
|
|
+ if strutils.IsStringEmpty(tableName) {
|
|
|
+ return 0, errors.New("没有传递表名")
|
|
|
+ }
|
|
|
+
|
|
|
+ if e == nil {
|
|
|
+ return 0, nil
|
|
|
+ }
|
|
|
+
|
|
|
+ entityType := reflect.TypeOf(e)
|
|
|
+ if !reflectutils.IsTypeStructOrStructPointer(entityType) {
|
|
|
+ return 0, errors.New("实体参数不是结构或结构指针")
|
|
|
+ }
|
|
|
+
|
|
|
+ fields, err := sql_mapping.DefaultUsage(e)
|
|
|
+ if err != nil {
|
|
|
+ return 0, err
|
|
|
+ }
|
|
|
+
|
|
|
+ now := time.Now().Local()
|
|
|
+ tableRow := sql.NewTableRow()
|
|
|
+ conditions := sql.NewConditions()
|
|
|
+
|
|
|
+ for _, field := range fields {
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+ if !field.IsKey && field.FieldName != lastUpdatedTimeFieldName &&
|
|
|
+ (!field.CanUpdate || (reflect.ValueOf(field.Value).IsZero() && !field.CanUpdateClear)) {
|
|
|
+ continue
|
|
|
+ }
|
|
|
+
|
|
|
+ fieldValue := reflect.ValueOf(field.Value)
|
|
|
+
|
|
|
+ if field.FieldName == lastUpdatedTimeFieldName &&
|
|
|
+ reflectutils.IsValueTime(fieldValue) && fieldValue.IsZero() {
|
|
|
+ field.Value = now
|
|
|
+ }
|
|
|
+
|
|
|
+ if field.FieldName != lastUpdatedTimeFieldName &&
|
|
|
+ reflectutils.IsValueTime(fieldValue) && fieldValue.IsZero() {
|
|
|
+ field.Value = nil
|
|
|
+ }
|
|
|
+
|
|
|
+ if field.IsKey {
|
|
|
+ conditions.Equal(field.ColumnName, field.Value)
|
|
|
+ } else {
|
|
|
+ if (field.Value == nil || reflect.ValueOf(field.Value).IsZero()) && !field.CanUpdateClear {
|
|
|
+ continue
|
|
|
+ }
|
|
|
+
|
|
|
+ tableRow.Add(field.ColumnName, field.Value)
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ executeParams := sql.UpdateExecuteParams{
|
|
|
+ TableName: tableName,
|
|
|
+ TableRow: tableRow,
|
|
|
+ Conditions: conditions,
|
|
|
+ }
|
|
|
+
|
|
|
+ executeParamsMap, err := executeParams.Map()
|
|
|
+ if err != nil {
|
|
|
+ return 0, err
|
|
|
+ }
|
|
|
+
|
|
|
+ args := make([]any, 0)
|
|
|
+ args = append(args, executeParams.TableRow.Values()...)
|
|
|
+ args = append(args, executeParams.Conditions.Args()...)
|
|
|
+
|
|
|
+ _, rowsAffected, err := executor.ExecuteRawSqlTemplateWithRowsAffected(sql.UpdateTpl, executeParamsMap, args...)
|
|
|
+ if err != nil {
|
|
|
+ return 0, err
|
|
|
+ }
|
|
|
+
|
|
|
+ return rowsAffected, nil
|
|
|
+}
|
|
|
+
|
|
|
|
|
|
|
|
|
|