dataset.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2015 The Xorm Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package xorm
  5. import (
  6. tablib "github.com/agrison/go-tablib"
  7. )
  8. // NewDataset creates a new Dataset.
  9. func NewDataset(headers []string) *tablib.Dataset {
  10. return tablib.NewDataset(headers)
  11. }
  12. // NewDatasetWithData creates a new Dataset.
  13. func NewDatasetWithData(headers []string, data interface{}, mustMatch bool) (*tablib.Dataset, error) {
  14. if data == nil {
  15. return tablib.NewDatasetWithData(headers, nil), nil
  16. }
  17. n := len(headers)
  18. switch data.(type) {
  19. case [][]interface{}:
  20. return tablib.NewDatasetWithData(headers, data.([][]interface{})), nil
  21. case []map[string]interface{}:
  22. dataSlice := data.([]map[string]interface{})
  23. if len(dataSlice) > 0 {
  24. if len(dataSlice[0]) == 0 {
  25. return tablib.NewDatasetWithData(headers, make([][]interface{}, len(dataSlice))), nil
  26. } else {
  27. if n != len(dataSlice[0]) && mustMatch {
  28. return nil, ErrParamsType
  29. }
  30. mapHeaders := make(map[string]int, n)
  31. for i := 0; i < n; i++ {
  32. mapHeaders[headers[i]] = i
  33. }
  34. for k, _ := range dataSlice[0] {
  35. if _, ok := mapHeaders[k]; !ok {
  36. return nil, ErrParamsType
  37. }
  38. }
  39. d := tablib.NewDataset(headers)
  40. var row []interface{}
  41. for i, _ := range dataSlice {
  42. row = nil
  43. for j := 0; j < n; j++ {
  44. row = append(row, dataSlice[i][headers[j]])
  45. }
  46. d.Append(row)
  47. }
  48. return d, nil
  49. }
  50. } else {
  51. return tablib.NewDatasetWithData(headers, nil), nil
  52. }
  53. default:
  54. return nil, ErrParamsType
  55. }
  56. }