csvreader.go 2.2 KB

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