csvreader.go 2.1 KB

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