csvreader.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package reader
  2. import (
  3. "fmt"
  4. "io"
  5. "strconv"
  6. "strings"
  7. "git.wecise.com/wecise/cgimport/schema"
  8. "github.com/spf13/cast"
  9. "github.com/wecisecode/util/merrs"
  10. )
  11. type CSVBlockReader struct {
  12. *LineReader
  13. filetype schema.FileType
  14. csvkeys []string
  15. }
  16. func NewCSVBlockReader(filename string, filetype schema.FileType, reader io.Reader) *CSVBlockReader {
  17. return &CSVBlockReader{
  18. LineReader: NewLineReader(filename, reader),
  19. filetype: filetype,
  20. }
  21. }
  22. func (br *CSVBlockReader) ReadBlock() (block map[string]any, line string, linecount int, err error) {
  23. classname := string(br.filetype)
  24. ci := schema.ClassInfos.GetIFPresent(classname)
  25. eof := false
  26. for {
  27. line, linecount, eof, err = br.ReadLine()
  28. if err != nil {
  29. return
  30. }
  31. if linecount == 1 {
  32. br.csvkeys = strings.Split(line, "^")
  33. line, linecount, eof, err = br.ReadLine()
  34. if err != nil {
  35. return
  36. }
  37. }
  38. if line == "" {
  39. if eof {
  40. return
  41. }
  42. continue
  43. }
  44. values := strings.Split(line, "^")
  45. if len(values) != len(br.csvkeys) {
  46. err = merrs.NewError(fmt.Sprint(br.filename, " format error, values count not match keys count, line ", br.linecount))
  47. return
  48. }
  49. block = map[string]any{}
  50. for i, k := range br.csvkeys {
  51. v := values[i]
  52. if v != "" {
  53. n := cast.ToInt64(v)
  54. if n != 0 || v == "0" {
  55. block[k] = n
  56. continue
  57. }
  58. f := cast.ToFloat64(v)
  59. if f != 0 || v == "0" || v == "0.0" || v == ".0" || v == "0." {
  60. block[k] = f
  61. continue
  62. }
  63. b := cast.ToBool(v)
  64. if v == "true" || v == "false" {
  65. block[k] = b
  66. continue
  67. }
  68. s, e := strconv.Unquote(v)
  69. if e == nil {
  70. v = s
  71. }
  72. }
  73. if ci != nil {
  74. fi := ci.DatakeyFieldinfos[k]
  75. if fi != nil {
  76. switch fi.Fieldtype {
  77. case "set<varchar>":
  78. s := v
  79. if strings.HasPrefix(s, "[") && strings.HasSuffix(s, "]") {
  80. s = s[1 : len(s)-1]
  81. }
  82. ss := cast.ToStringSlice(s)
  83. block[k] = ss
  84. continue
  85. case "varchar":
  86. block[k] = cast.ToString(v)
  87. continue
  88. case "bigint":
  89. block[k] = cast.ToInt64(v)
  90. continue
  91. }
  92. }
  93. }
  94. block[k] = v
  95. }
  96. return
  97. }
  98. }