Browse Source

修改bug

yjp 11 months ago
parent
commit
6ed58f22fd

+ 2 - 6
application/config.go

@@ -2,7 +2,7 @@ package application
 
 import (
 	"encoding/json"
-	"git.sxidc.com/go-framework/baize/infrastructure/database/operations"
+	"git.sxidc.com/go-framework/baize/infrastructure"
 	"git.sxidc.com/go-tools/utils/fileutils"
 	"git.sxidc.com/service-supports/fserr"
 	"gopkg.in/yaml.v3"
@@ -20,11 +20,7 @@ type ApiConfig struct {
 }
 
 type InfrastructureConfig struct {
-	Database InfrastructureDatabase
-}
-
-type InfrastructureDatabase struct {
-	Operations *operations.Config
+	Database infrastructure.DatabaseConfig `json:"database" yaml:"database"`
 }
 
 func LoadFromJsonFile(jsonFilePath string) (Config, error) {

+ 8 - 0
baize.go

@@ -31,3 +31,11 @@ func NewApplication(conf application.Config) *application.App {
 
 	return application.New(apiInstance, infrastructureInstance)
 }
+
+func DestroyApplication(app *application.App) {
+	if app == nil {
+		return
+	}
+
+	infrastructure.DestroyInfrastructure(app.Infrastructure())
+}

+ 12 - 1
binding/binding.go

@@ -12,6 +12,12 @@ import (
 	"strings"
 )
 
+var globalInfrastructure *infrastructure.Infrastructure
+
+func SetGlobalInfrastructure(i *infrastructure.Infrastructure) {
+	globalInfrastructure = i
+}
+
 func PostBind[O any](router api.Router, item *SimpleBindItem[O], middlewares ...api.Handler) {
 	item.bind(router, http.MethodPost, middlewares...)
 }
@@ -198,7 +204,12 @@ func (item *BindItem[O]) bind(router api.Router, middlewares ...api.Handler) {
 			// 执行业务函数
 			statusCode := http.StatusOK
 
-			outputModel, err := item.ServiceFunc(c, dto, domainObjects, item.Infrastructure)
+			i := globalInfrastructure
+			if item.Infrastructure != nil {
+				i = item.Infrastructure
+			}
+
+			outputModel, err := item.ServiceFunc(c, dto, domainObjects, i)
 			if err != nil {
 				statusCode = fserr.ParseCode(err).HttpCode
 			}

+ 7 - 11
binding/dto.go

@@ -4,6 +4,7 @@ import (
 	"git.sxidc.com/go-framework/baize/domain"
 	"git.sxidc.com/go-framework/baize/infrastructure/logger"
 	"git.sxidc.com/go-framework/baize/tag/assign"
+	"git.sxidc.com/go-tools/utils/reflectutils"
 	"git.sxidc.com/service-supports/fserr"
 	"reflect"
 )
@@ -52,22 +53,17 @@ func ToConcreteDTO[T DTO](object DTO) T {
 }
 
 func getDTOFieldValue(dto DTO, fieldName string) (*reflect.Value, error) {
-	dtoType := reflect.TypeOf(dto)
-
-	if dtoType.Kind() != reflect.Pointer {
-		return nil, fserr.New("dto必须是结构指针类型")
-	}
-
-	if dtoType.Kind() == reflect.Pointer && dtoType.Elem().Kind() != reflect.Struct {
-		return nil, fserr.New("dto必须是结构指针类型")
+	if dto == nil {
+		return nil, fserr.New("dto为nil")
 	}
 
 	dtoValue := reflect.ValueOf(dto)
-	if dtoType.Kind() == reflect.Pointer && !dtoValue.IsValid() {
-		return nil, fserr.New("dto为nil")
+
+	if reflectutils.IsValueStructOrStructPointer(dtoValue) {
+		return nil, fserr.New("dto必须是结构或结构指针")
 	}
 
-	fieldValue := dtoValue.Elem().FieldByName(fieldName)
+	fieldValue := reflectutils.PointerValueElem(dtoValue).FieldByName(fieldName)
 
 	return &fieldValue, nil
 }

+ 7 - 11
domain/object.go

@@ -2,6 +2,7 @@ package domain
 
 import (
 	"git.sxidc.com/go-framework/baize/infrastructure/logger"
+	"git.sxidc.com/go-tools/utils/reflectutils"
 	"git.sxidc.com/service-supports/fserr"
 	"reflect"
 )
@@ -62,22 +63,17 @@ func ToConcreteObject[T Object](object Object) T {
 }
 
 func getObjectFieldValue(object Object, fieldName string) (*reflect.Value, error) {
-	objectType := reflect.TypeOf(object)
-
-	if objectType.Kind() != reflect.Pointer {
-		return nil, fserr.New("object必须是结构指针类型")
-	}
-
-	if objectType.Kind() == reflect.Pointer && objectType.Elem().Kind() != reflect.Struct {
-		return nil, fserr.New("object必须是结构指针类型")
+	if object == nil {
+		return nil, fserr.New("object为nil")
 	}
 
 	objectValue := reflect.ValueOf(object)
-	if objectType.Kind() == reflect.Pointer && !objectValue.IsValid() {
-		return nil, fserr.New("object为nil")
+
+	if reflectutils.IsValueStructOrStructPointer(objectValue) {
+		return nil, fserr.New("object必须是结构或结构指针")
 	}
 
-	fieldValue := objectValue.Elem().FieldByName(fieldName)
+	fieldValue := reflectutils.PointerValueElem(objectValue).FieldByName(fieldName)
 
 	return &fieldValue, nil
 }

+ 157 - 78
examples/binding/main.go

@@ -1,23 +1,26 @@
 package main
 
 import (
-	"fmt"
 	"git.sxidc.com/go-framework/baize"
 	"git.sxidc.com/go-framework/baize/api"
 	"git.sxidc.com/go-framework/baize/application"
 	"git.sxidc.com/go-framework/baize/binding"
 	"git.sxidc.com/go-framework/baize/domain"
 	"git.sxidc.com/go-framework/baize/infrastructure"
+	"git.sxidc.com/go-framework/baize/infrastructure/database"
+	"git.sxidc.com/go-framework/baize/infrastructure/database/operations"
+	"git.sxidc.com/go-framework/baize/infrastructure/database/sql"
 	"git.sxidc.com/go-tools/utils/strutils"
 	DEATH "github.com/vrecan/death"
 	"syscall"
+	"time"
 )
 
 // curl -X POST -H "Content-Type: application/json" -d '{"name":"test"}' "http://localhost:10000/test/v1/class/create"
-// curl -X PUT -H "Content-Type: application/json" -d '{"id":"47748950c1c74e8c9cd9dc913996fc8b", "name":"test-new"}' "http://localhost:10000/test/v1/class/update"
+// curl -X PUT -H "Content-Type: application/json" -d '{"id":"ab0d4a9acce44ddd91ad4746ecd34392", "name":"test-new"}' "http://localhost:10000/test/v1/class/update"
 // curl -X GET "http://localhost:10000/test/v1/class/query?name=test-new&pageNo=0&pageSize=1"
-// curl -X GET "http://localhost:10000/test/v1/class/get?id=47748950c1c74e8c9cd9dc913996fc8b"
-// curl -X DELETE "http://localhost:10000/test/v1/class/47748950c1c74e8c9cd9dc913996fc8b/delete"
+// curl -X GET "http://localhost:10000/test/v1/class/get?id=ab0d4a9acce44ddd91ad4746ecd34392"
+// curl -X DELETE "http://localhost:10000/test/v1/class/ab0d4a9acce44ddd91ad4746ecd34392/delete"
 
 type CreateClassJsonBody struct {
 	Name string `json:"name" binding:"required" assign:"toField:Name"`
@@ -42,17 +45,31 @@ type GetClassQueryParams struct {
 	ID string `form:"id" binding:"required" assign:"toField:ID"`
 }
 
+type DomainIDField struct {
+	ID string `sqlmapping:"column:id"`
+}
+
 type Class struct {
-	ID   string
-	Name string
+	*DomainIDField
+	Name            string `sqlmapping:"column:name"`
+	CreatedTime     time.Time
+	LastUpdatedTime *time.Time
+}
+
+type InfoIDField struct {
+	ID string `json:"id" sqlresult:"column:id"`
 }
 
 type ClassInfo struct {
-	ID   string `json:"id"`
-	Name string `json:"name"`
+	*InfoIDField
+	Name            string `json:"name" sqlresult:"column:name"`
+	CreatedTime     string `sqlresult:"parseTime:'2006-01-02 15:04:05'"`
+	LastUpdatedTime string `sqlresult:"parseTime:'2006-01-02 15:04:05'"`
 }
 
-var classMap = make(map[string]domain.Object)
+const (
+	tableName = "test.classes"
+)
 
 func main() {
 	app := baize.NewApplication(application.Config{
@@ -60,10 +77,66 @@ func main() {
 			UrlPrefix: "test",
 			Port:      "10000",
 		},
+		InfrastructureConfig: application.InfrastructureConfig{
+			Database: infrastructure.DatabaseConfig{
+				Operations: &operations.Config{
+					UserName:           "test",
+					Password:           "123456",
+					Address:            "localhost",
+					Port:               "30432",
+					Database:           "test",
+					MaxConnections:     40,
+					MaxIdleConnections: 10,
+				},
+			},
+		},
+	})
+
+	defer func() {
+		baize.DestroyApplication(app)
+	}()
+
+	dbOperations := app.Infrastructure().GetDBOperations()
+	err := dbOperations.AutoMigrate(operations.Table{
+		TableName: tableName,
+		Columns: []operations.TableColumn{
+			{
+				Name:       "id",
+				Type:       "varchar(32)",
+				Comment:    "id",
+				PrimaryKey: true,
+			},
+			{
+				Name:    "name",
+				Type:    "varchar(128)",
+				Comment: "名称",
+				NotNull: true,
+				Index:   true,
+			},
+			{
+				Name:    "created_time",
+				Type:    "timestamp with time zone",
+				Comment: "创建时间",
+				NotNull: true,
+				Index:   true,
+			},
+			{
+				Name:    "last_updated_time",
+				Type:    "timestamp with time zone",
+				Comment: "更新时间",
+				NotNull: true,
+				Index:   true,
+			},
+		},
 	})
+	if err != nil {
+		panic(err)
+	}
 
 	v1Router := app.Api().PrefixRouter().RegisterVersionedRouter("v1")
 
+	binding.SetGlobalInfrastructure(app.Infrastructure())
+
 	// 创建班级
 	binding.PostBind(v1Router, &binding.SimpleBindItem[string]{
 		Path:         "/class/create",
@@ -73,7 +146,12 @@ func main() {
 		ServiceFunc: func(c *api.Context, dto binding.DTO, objects []domain.Object, i *infrastructure.Infrastructure) (string, error) {
 			e := domain.ToConcreteObject[*Class](objects[0])
 			e.ID = strutils.SimpleUUID()
-			classMap[e.ID] = e
+
+			err := database.InsertEntity(i.GetDBOperations(), tableName, e)
+			if err != nil {
+				return "", err
+			}
+
 			return e.ID, nil
 		},
 	})
@@ -85,9 +163,13 @@ func main() {
 		DTO:          &DeleteClassPathParams{},
 		Objects:      []domain.Object{&Class{}},
 		ServiceFunc: func(c *api.Context, dto binding.DTO, objects []domain.Object, i *infrastructure.Infrastructure) (any, error) {
-			id := domain.Field[string](objects[0], "ID")
-			delete(classMap, id)
-			fmt.Println("Deleted Entity:" + id)
+			e := domain.ToConcreteObject[*Class](objects[0])
+
+			err := database.DeleteEntity(i.GetDBOperations(), tableName, e)
+			if err != nil {
+				return "", err
+			}
+
 			return nil, nil
 		},
 	})
@@ -99,20 +181,34 @@ func main() {
 		DTO:          &UpdateClassJsonBody{},
 		Objects:      []domain.Object{&Class{}},
 		ServiceFunc: func(c *api.Context, dto binding.DTO, objects []domain.Object, i *infrastructure.Infrastructure) (any, error) {
-			id := domain.Field[string](objects[0], "ID")
-			newName := domain.Field[string](objects[0], "Name")
-
-			existEntity, ok := classMap[id]
-			if !ok {
-				fmt.Println("Update Entity:" + id)
-				fmt.Println("Not Find")
-				return nil, nil
+			e := domain.ToConcreteObject[*Class](objects[0])
+
+			result, err := database.QueryOne(i.GetDBOperations(), &sql.QueryOneExecuteParams{
+				TableName:  tableName,
+				Conditions: sql.NewConditions().Equal("id", e.ID),
+			})
+			if err != nil {
+				return nil, err
+			}
+
+			existClass := new(Class)
+			err = sql.ParseSqlResult(result, existClass)
+			if err != nil {
+				return nil, err
+			}
+
+			newEntity := &Class{
+				DomainIDField: &DomainIDField{ID: existClass.ID},
 			}
 
-			domain.SetField(existEntity, "Name", newName)
+			if strutils.IsStringNotEmpty(e.Name) && e.Name != existClass.Name {
+				newEntity.Name = e.Name
+			}
 
-			fmt.Println("Update Entity:" + id)
-			fmt.Println("Name:" + newName)
+			err = database.UpdateEntity(i.GetDBOperations(), tableName, newEntity)
+			if err != nil {
+				return "", err
+			}
 
 			return nil, nil
 		},
@@ -125,60 +221,39 @@ func main() {
 		DTO:          &QueryClassesQueryParams{},
 		Objects:      []domain.Object{&Class{}},
 		ServiceFunc: func(c *api.Context, dto binding.DTO, objects []domain.Object, i *infrastructure.Infrastructure) (binding.InfosData[ClassInfo], error) {
-			name := domain.Field[string](objects[0], "Name")
-
-			classInfos := make([]ClassInfo, 0)
-
+			e := domain.ToConcreteObject[*Class](objects[0])
 			pageNo := binding.Field[int](dto, "PageNo")
 			pageSize := binding.Field[int](dto, "PageSize")
 
-			startCount := 1
-			if pageNo != 0 && pageSize != 0 {
-				startCount = pageNo*pageSize + 1
+			conditions := sql.NewConditions()
+
+			if strutils.IsStringNotEmpty(e.Name) {
+				conditions.Equal("name", e.Name)
 			}
 
-			needFindCount := len(classMap)
-			if pageNo != 0 && pageSize != 0 {
-				needFindCount = pageSize
+			results, totalCount, err := database.Query(i.GetDBOperations(), &sql.QueryExecuteParams{
+				TableName:  tableName,
+				Conditions: conditions,
+				PageNo:     pageNo,
+				PageSize:   pageSize,
+			})
+			if err != nil {
+				return binding.InfosData[ClassInfo]{
+					Infos: make([]ClassInfo, 0),
+				}, nil
 			}
 
-			count := 1
-			findCount := 0
-
-			for _, existEntity := range classMap {
-				existID := domain.Field[string](existEntity, "ID")
-				existName := domain.Field[string](existEntity, "Name")
-
-				if findCount >= needFindCount {
-					break
-				}
-
-				if count >= startCount {
-					find := false
-					if strutils.IsStringNotEmpty(name) {
-						if existName == name {
-							find = true
-							findCount++
-						}
-					} else {
-						find = true
-						findCount++
-					}
-
-					if find {
-						classInfos = append(classInfos, ClassInfo{
-							ID:   existID,
-							Name: existName,
-						})
-					}
-				}
-
-				count++
+			classInfos := make([]ClassInfo, 0)
+			err = sql.ParseSqlResult(results, &classInfos)
+			if err != nil {
+				return binding.InfosData[ClassInfo]{
+					Infos: make([]ClassInfo, 0),
+				}, nil
 			}
 
 			return binding.InfosData[ClassInfo]{
 				Infos:      classInfos,
-				TotalCount: int64(len(classMap)),
+				TotalCount: totalCount,
 				PageNo:     pageNo,
 			}, nil
 		},
@@ -191,19 +266,23 @@ func main() {
 		DTO:          &GetClassQueryParams{},
 		Objects:      []domain.Object{&Class{}},
 		ServiceFunc: func(c *api.Context, dto binding.DTO, objects []domain.Object, i *infrastructure.Infrastructure) (*ClassInfo, error) {
-			id := domain.Field[string](objects[0], "ID")
-
-			classInfo := new(ClassInfo)
-			for _, existEntity := range classMap {
-				if domain.Field[string](existEntity, "ID") == id {
-					classInfo = &ClassInfo{
-						ID:   domain.Field[string](existEntity, "ID"),
-						Name: domain.Field[string](existEntity, "Name"),
-					}
-				}
+			e := domain.ToConcreteObject[*Class](objects[0])
+
+			result, err := database.QueryOne(i.GetDBOperations(), &sql.QueryOneExecuteParams{
+				TableName:  tableName,
+				Conditions: sql.NewConditions().Equal("id", e.ID),
+			})
+			if err != nil {
+				return nil, err
+			}
+
+			info := new(ClassInfo)
+			err = sql.ParseSqlResult(result, info)
+			if err != nil {
+				return nil, err
 			}
 
-			return classInfo, nil
+			return info, nil
 		},
 	})
 

+ 1 - 1
go.mod

@@ -3,7 +3,7 @@ module git.sxidc.com/go-framework/baize
 go 1.22.3
 
 require (
-	git.sxidc.com/go-tools/utils v1.5.10
+	git.sxidc.com/go-tools/utils v1.5.11
 	git.sxidc.com/service-supports/fserr v0.3.5
 	git.sxidc.com/service-supports/fslog v0.5.9
 	git.sxidc.com/service-supports/websocket v1.3.1

+ 2 - 2
go.sum

@@ -1,5 +1,5 @@
-git.sxidc.com/go-tools/utils v1.5.10 h1:mZmitAT0hQwfv6ZOFTHJ2Q1nfWY+GeF3TrV74WAxbrI=
-git.sxidc.com/go-tools/utils v1.5.10/go.mod h1:fkobAXFpOMTvkZ82TQXWcpsayePcyk/MS5TN6GTlRDg=
+git.sxidc.com/go-tools/utils v1.5.11 h1:Abpvvx+cntwRY3zNHor9hD5nI3Xx6uIfc5kup1kf+ok=
+git.sxidc.com/go-tools/utils v1.5.11/go.mod h1:fkobAXFpOMTvkZ82TQXWcpsayePcyk/MS5TN6GTlRDg=
 git.sxidc.com/service-supports/fserr v0.3.5 h1:1SDC60r3FIDd2iRq/oHRLK4OMa1gf67h9B7kierKTUE=
 git.sxidc.com/service-supports/fserr v0.3.5/go.mod h1:8U+W/ulZIGVPFojV6cE18shkGXqvaICuzaxIJpOcBqI=
 git.sxidc.com/service-supports/fslog v0.5.9 h1:q2XIK2o/fk/qmByy4x5kKLC+k7kolT5LrXHcWRSffXQ=

+ 1 - 1
infrastructure/database/database.go

@@ -210,7 +210,7 @@ func UpdateEntity(executor Executor, tableName string, e any) error {
 		// 不是键字段
 		// 不是更新时间字段
 		// 不更新的字段或者字段为零值且不能清空,跳过
-		if field.FieldName != lastUpdatedTimeFieldName &&
+		if !field.IsKey && field.FieldName != lastUpdatedTimeFieldName &&
 			(!field.CanUpdate || (reflect.ValueOf(field.Value).IsZero() && !field.CanUpdateClear)) {
 			continue
 		}

+ 78 - 0
infrastructure/database/sql/result.go

@@ -1,8 +1,11 @@
 package sql
 
 import (
+	"errors"
 	"fmt"
+	"git.sxidc.com/go-framework/baize/tag/sql/sql_result"
 	"git.sxidc.com/go-tools/utils/reflectutils"
+	"reflect"
 	"strings"
 	"time"
 )
@@ -13,6 +16,81 @@ const (
 	resultTimeSecFormat   = "2006-01-02T15:04:05+08:00"
 )
 
+func ParseSqlResult(input any, e any) error {
+	if input == nil {
+		return nil
+	}
+
+	if e == nil {
+		return nil
+	}
+
+	results, ok := input.([]Result)
+	if !ok {
+		tableRow, ok := input.(Result)
+		if !ok {
+			return errors.New("输入数据应该为sdk.SqlResult或[]sdk.SqlResult")
+		}
+
+		results = []Result{tableRow}
+	}
+
+	typeCheckErr := errors.New("可以接受的输出类型为结构指针或者结构slice的指针")
+	outputValue := reflect.ValueOf(e)
+
+	if outputValue.Kind() != reflect.Pointer {
+		return typeCheckErr
+	} else {
+		outputElemValue := reflectutils.PointerValueElem(outputValue)
+
+		if outputElemValue.Kind() != reflect.Struct && outputElemValue.Kind() != reflect.Slice {
+			return typeCheckErr
+		}
+
+		if outputElemValue.Kind() == reflect.Slice && !reflectutils.IsSliceValueOf(outputElemValue, reflect.Struct) {
+			return typeCheckErr
+		}
+	}
+
+	outputElemValue := reflectutils.PointerValueElem(outputValue)
+
+	// 构造输出实体slice
+	var outputEntities reflect.Value
+	if outputElemValue.Kind() == reflect.Struct {
+		outputEntities = reflect.MakeSlice(reflect.SliceOf(outputElemValue.Type()), 0, 0)
+	} else {
+		outputEntities = reflect.MakeSlice(outputElemValue.Type(), 0, 0)
+	}
+
+	for _, result := range results {
+		var outputEntityValue reflect.Value
+		if outputElemValue.Kind() == reflect.Struct {
+			outputEntityValue = reflect.New(outputElemValue.Type()).Elem()
+		} else {
+			outputEntityValue = reflect.New(outputElemValue.Type().Elem()).Elem()
+		}
+
+		outputEntity := outputEntityValue.Addr().Interface()
+
+		err := sql_result.DefaultUsage(result, outputEntity)
+		if err != nil {
+			return err
+		}
+
+		// 保存输出实体
+		outputEntities = reflect.Append(outputEntities, outputEntityValue)
+	}
+
+	// 将输出实体赋值给输出指针变量
+	if outputElemValue.Kind() == reflect.Slice {
+		outputElemValue.Set(outputEntities)
+	} else {
+		outputElemValue.Set(outputEntities.Index(0))
+	}
+
+	return nil
+}
+
 type Result map[string]any
 
 func (result Result) ColumnValueStringAsTime(columnName string) time.Time {

+ 7 - 0
infrastructure/database/sql/value.go

@@ -5,6 +5,11 @@ import (
 	"git.sxidc.com/service-supports/fserr"
 	"reflect"
 	"strings"
+	"time"
+)
+
+const (
+	timeWriteFormat = time.DateTime + ".000000 +08:00"
 )
 
 func toSqlValue(value any) (string, error) {
@@ -21,6 +26,8 @@ func toSqlValue(value any) (string, error) {
 	switch v := reflectutils.PointerValueElem(valueValue).Interface().(type) {
 	case string:
 		return "'" + v + "'", nil
+	case time.Time:
+		return "'" + v.Format(timeWriteFormat) + "'", nil
 	default:
 		var retStr string
 		err := reflectutils.AssignStringValue(v, reflect.ValueOf(retStr))

+ 3 - 3
infrastructure/infrastructure.go

@@ -33,9 +33,9 @@ func NewInfrastructure(config Config) *Infrastructure {
 	return i
 }
 
-func DestroyInfrastructure(i *Infrastructure) error {
+func DestroyInfrastructure(i *Infrastructure) {
 	if i == nil {
-		return nil
+		return
 	}
 
 	if i.dbOperations != nil {
@@ -45,7 +45,7 @@ func DestroyInfrastructure(i *Infrastructure) error {
 		}
 	}
 
-	return nil
+	return
 }
 
 func (i Infrastructure) GetDBOperations() *operations.Operations {

+ 2 - 12
tag/sql/sql_mapping/usage.go

@@ -7,11 +7,6 @@ import (
 	"git.sxidc.com/service-supports/fserr"
 	"reflect"
 	"strings"
-	"time"
-)
-
-const (
-	timeWriteFormat = time.DateTime + ".000000 +08:00"
 )
 
 type Field struct {
@@ -44,7 +39,7 @@ func defaultCallback(fields *[]Field) OnParsedFieldTagFunc {
 			CanUpdateClear: tag.CanUpdateClear,
 		}
 
-		if entityFieldElemValue.IsZero() {
+		if entityFieldElemValue.IsZero() && !reflectutils.IsValueTime(entityFieldElemValue) {
 			reflectutils.Zero(&entityFieldElemValue)
 			field.Value = entityFieldElemValue.Interface()
 			*fields = append(*fields, field)
@@ -59,12 +54,7 @@ func defaultCallback(fields *[]Field) OnParsedFieldTagFunc {
 				return fserr.New(fieldName + " Error: 解析tag内部错误,除time.Time类型之外的结构被回调")
 			}
 
-			strValue, err := dealStringValue(entityFieldElemValue.Interface().(time.Time).Format(timeWriteFormat), tag)
-			if err != nil {
-				return err
-			}
-
-			field.Value = strValue
+			field.Value = entityFieldElemValue.Interface()
 		case reflect.Slice:
 			if !reflectutils.IsSliceValueOf(entityFieldElemValue, reflect.String) {
 				return fserr.New(fieldName + " Error: slice仅支持[]string")

+ 17 - 11
tag/sql/sql_result/usage.go

@@ -12,9 +12,9 @@ import (
 )
 
 const (
-	sqlResultTimeMicroFormat = "2006-01-02T15:04:05.000000+08:00"
-	sqlResultTimeMilliFormat = "2006-01-02T15:04:05.000+08:00"
-	sqlResultTimeSecFormat   = "2006-01-02T15:04:05+08:00"
+	timeMicroFormat = "2006-01-02T15:04:05.000000"
+	timeMilliFormat = "2006-01-02T15:04:05.000"
+	timeSecFormat   = "2006-01-02T15:04:05"
 )
 
 func DefaultUsage(result map[string]any, e any) error {
@@ -116,14 +116,20 @@ func defaultCallback(result map[string]any) OnParsedFieldTagFunc {
 }
 
 func parseTimeStringResult(timeStr string) (time.Time, error) {
-	var layout string
-
-	if strings.HasSuffix(timeStr, ".000000+08:00") {
-		layout = sqlResultTimeMicroFormat
-	} else if strings.HasSuffix(timeStr, ".000+08:00") {
-		layout = sqlResultTimeMilliFormat
-	} else {
-		layout = sqlResultTimeSecFormat
+	layout := timeSecFormat
+
+	timeZoneIndex := strings.LastIndex(timeStr, "+08:")
+	if timeZoneIndex != -1 {
+		timeStr = timeStr[:timeZoneIndex]
+
+		afterSecondIndex := strings.LastIndex(timeStr, ".")
+		if afterSecondIndex != -1 {
+			if len(timeStr)-afterSecondIndex-1 == 6 {
+				layout = timeMicroFormat
+			} else if len(timeStr)-afterSecondIndex-1 == 3 {
+				layout = timeMilliFormat
+			}
+		}
 	}
 
 	return time.ParseInLocation(layout, timeStr, time.Local)