forked from daptin/daptin
/
action_csv_to_entity.go
204 lines (160 loc) · 4.66 KB
/
action_csv_to_entity.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package resource
import (
"bytes"
"encoding/base64"
"fmt"
"github.com/artpar/api2go"
"github.com/daptin/daptin/server/columntypes"
"github.com/daptin/daptin/server/csvmap"
"github.com/gin-gonic/gin/json"
log "github.com/sirupsen/logrus"
"io/ioutil"
"strings"
)
type UploadCsvFileToEntityPerformer struct {
responseAttrs map[string]interface{}
cruds map[string]*DbResource
cmsConfig *CmsConfig
}
func (d *UploadCsvFileToEntityPerformer) Name() string {
return "__upload_csv_file_to_entity"
}
func (d *UploadCsvFileToEntityPerformer) DoAction(request ActionRequest, inFields map[string]interface{}) (api2go.Responder, []ActionResponse, []error) {
//actions := make([]ActionResponse, 0)
log.Infof("Do action: %v", d.Name())
files := inFields["data_csv_file"].([]interface{})
entityName := inFields["entity_name"].(string)
create_if_not_exists := inFields["create_if_not_exists"].(bool)
add_missing_columns := inFields["add_missing_columns"].(bool)
table := TableInfo{}
table.TableName = SmallSnakeCaseText(entityName)
columns := make([]api2go.ColumnInfo, 0)
allSt := make(map[string]interface{})
sources := make([]DataFileImport, 0)
completed := false
var existingEntity *TableInfo
if !create_if_not_exists {
var ok bool
dbr, ok := d.cruds[entityName]
if !ok {
return nil, nil, []error{fmt.Errorf("no such entity: %v", entityName)}
}
existingEntity = dbr.tableInfo
}
for _, fileInterface := range files {
file := fileInterface.(map[string]interface{})
fileName := file["name"].(string)
fileContentsBase64 := file["file"].(string)
fileBytes, err := base64.StdEncoding.DecodeString(strings.Split(fileContentsBase64, ",")[1])
log.Infof("Processing file: %v", fileName)
CheckErr(err, "Uploaded file is not a valid csv file")
if err != nil {
return nil, nil, []error{err}
}
err = ioutil.WriteFile(fileName, fileBytes, 0644)
if err != nil {
log.Errorf("Failed to write xls file to disk: %v", err)
}
csvReader := csvmap.NewReader(bytes.NewReader(fileBytes))
columnNames, err := csvReader.ReadHeader()
if err != nil {
return nil, nil, []error{err}
}
csvReader.Columns = columnNames
data, err := csvReader.ReadAll()
recordCount := len(data)
if err != nil {
return nil, nil, []error{err}
}
if err != nil {
return nil, nil, []error{err}
}
// identify data type of each column
for _, colName := range columnNames {
if colName == "" {
continue
}
var column api2go.ColumnInfo
if add_missing_columns && existingEntity != nil {
_, ok := existingEntity.GetColumnByName(colName)
if !ok {
// ignore column if it doesn't exists
continue
}
}
dataMap := map[string]bool{}
datas := make([]string, 0)
isNullable := false
count := 100000
for _, d := range data {
if count < 0 {
break
}
i := d[colName]
var strVal string
if i == "" {
isNullable = true
continue
} else {
strVal = i
}
if dataMap[strVal] {
continue
}
dataMap[strVal] = true
datas = append(datas, strVal)
count -= 1
}
eType, _, err := fieldtypes.DetectType(datas)
if err != nil {
column.ColumnType = "label"
column.DataType = "varchar(100)"
} else {
column.ColumnType = EntityTypeToColumnTypeMap[eType]
column.DataType = EntityTypeToDataTypeMap[eType]
}
if len(datas) > (recordCount / 10) {
column.IsIndexed = true
}
if len(datas) == recordCount {
column.IsUnique = true
}
column.IsNullable = isNullable
column.Name = colName
column.ColumnName = SmallSnakeCaseText(colName)
columns = append(columns, column)
}
table.Columns = columns
completed = true
sources = append(sources, DataFileImport{FilePath: fileName, Entity: table.TableName, FileType: "csv"})
}
if completed {
if create_if_not_exists {
allSt["tables"] = []TableInfo{table}
}
allSt["imports"] = sources
jsonStr, err := json.Marshal(allSt)
if err != nil {
InfoErr(err, "Failed to convert object to json")
return nil, nil, []error{err}
}
jsonFileName := fmt.Sprintf("schema_%v_daptin.json", entityName)
ioutil.WriteFile(jsonFileName, jsonStr, 0644)
log.Printf("File %v written to disk for upload", jsonFileName)
if create_if_not_exists || add_missing_columns {
go restart()
} else {
ImportDataFiles(d.cmsConfig, d.cruds[entityName].db, d.cruds)
}
return nil, successResponses, nil
} else {
return nil, failedResponses, nil
}
}
func NewUploadCsvFileToEntityPerformer(initConfig *CmsConfig, cruds map[string]*DbResource) (ActionPerformerInterface, error) {
handler := UploadCsvFileToEntityPerformer{
cruds: cruds,
cmsConfig: initConfig,
}
return &handler, nil
}