value.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package sql_tpl
  2. import (
  3. "errors"
  4. "reflect"
  5. "strconv"
  6. "time"
  7. )
  8. const (
  9. timeWriteFormat = time.DateTime + ".000000 +08:00"
  10. )
  11. func parseValue(value any) (string, error) {
  12. valueValue := reflect.ValueOf(value)
  13. if !valueValue.IsValid() {
  14. return "", errors.New("无效值")
  15. }
  16. if valueValue.Kind() == reflect.Ptr && valueValue.IsNil() {
  17. return "", errors.New("空值")
  18. }
  19. if valueValue.Kind() == reflect.Ptr {
  20. valueValue = valueValue.Elem()
  21. }
  22. switch v := valueValue.Interface().(type) {
  23. case string:
  24. return "'" + v + "'", nil
  25. case bool:
  26. return strconv.FormatBool(v), nil
  27. case time.Time:
  28. return "'" + v.Format(timeWriteFormat) + "'", nil
  29. case int:
  30. return strconv.Itoa(v), nil
  31. case int8:
  32. return strconv.FormatInt(int64(v), 10), nil
  33. case int16:
  34. return strconv.FormatInt(int64(v), 10), nil
  35. case int32:
  36. return strconv.FormatInt(int64(v), 10), nil
  37. case int64:
  38. return strconv.FormatInt(v, 10), nil
  39. case uint:
  40. return strconv.FormatUint(uint64(v), 10), nil
  41. case uint8:
  42. return strconv.FormatUint(uint64(v), 10), nil
  43. case uint16:
  44. return strconv.FormatUint(uint64(v), 10), nil
  45. case uint32:
  46. return strconv.FormatUint(uint64(v), 10), nil
  47. case uint64:
  48. return strconv.FormatUint(v, 10), nil
  49. default:
  50. return "", errors.New("不支持的类型")
  51. }
  52. }