-
Notifications
You must be signed in to change notification settings - Fork 4
/
cleansing_functions.go
466 lines (448 loc) · 12.6 KB
/
cleansing_functions.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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
package main
import (
"database/sql"
"fmt"
"log"
"math"
"regexp"
"strconv"
"strings"
"unicode"
"github.com/artisoft-io/jetstore/jets/bridge"
"github.com/artisoft-io/jetstore/jets/datatable/jcsv"
)
type ConcatFunctionArg struct {
Delimit string
ColumnPositions []int
}
func ParseConcatFunctionArgument(rawArg *string, functionName string, inputColumnName2Pos map[string]int, cache map[string]interface{}) (*ConcatFunctionArg, error) {
// rawArg is csv-encoded
if rawArg == nil {
return nil, fmt.Errorf("unexpected null argument to %s function", functionName)
}
// Check if we have it cached
v := cache[*rawArg]
if v != nil {
// fmt.Println("*** OK Got Cached value for", *rawArg)
return v.(*ConcatFunctionArg), nil
}
// Parsed the raw argument into ConcatFunctionArg and put it in the cache
rows, err := jcsv.Parse(*rawArg)
if len(rows)==0 || len(rows[0])==0 || err != nil {
// It's not csv or there's no data
return nil, fmt.Errorf("error:no-data: argument %s cannot be parsed as csv: %v (%s function)", *rawArg, err, functionName)
}
results := &ConcatFunctionArg{
ColumnPositions: make([]int, 0),
}
for i := range rows[0] {
if i==0 && functionName=="concat_with" {
results.Delimit = rows[0][i]
} else {
colPos, ok := inputColumnName2Pos[rows[0][i]]
// fmt.Println("*** concat:",row[i],"value @:", colPos,"ok?",ok)
if !ok {
// Column not found
return nil, fmt.Errorf("error:column-not-fount: argument %s is not an input column name (%s function)", *rawArg, functionName)
}
results.ColumnPositions = append(results.ColumnPositions, colPos)
}
}
cache[*rawArg] = results
return results, nil
}
type SubStringFunctionArg struct {
Start int
End int
}
func ParseSubStringFunctionArgument(rawArg *string, functionName string, cache map[string]interface{}) (*SubStringFunctionArg, error) {
// rawArg is comma separated as: start,end
if rawArg == nil {
return nil, fmt.Errorf("unexpected null argument to %s function", functionName)
}
// Check if we have it cached
v := cache[*rawArg]
if v != nil {
// fmt.Println("*** OK Got Cached value for", *rawArg,":",v)
return v.(*SubStringFunctionArg), nil
}
// Parsed the raw argument into SubStringFunctionArg and put it in the cache
row := strings.Split(*rawArg, ",")
if len(row) != 2 {
// The argument is not valid
return nil, fmt.Errorf("error: argument %s cannot be parsed as start,end (%s function)", *rawArg, functionName)
}
start, err := strconv.Atoi(strings.TrimSpace(row[0]))
if err != nil {
return nil, fmt.Errorf("error: argument %s cannot be parsed as start,end: %v (%s function)", *rawArg, err, functionName)
}
end, err := strconv.Atoi(strings.TrimSpace(row[1]))
if err != nil || (end > 0 && end <= start) {
return nil, fmt.Errorf("error: argument %s cannot be parsed as start,end: %v (%s function)", *rawArg, err, functionName)
}
results := &SubStringFunctionArg{
Start: start,
End: end,
}
cache[*rawArg] = results
return results, nil
}
type FindReplaceFunctionArg struct {
Find string
ReplaceWith string
}
func ParseFindReplaceFunctionArgument(rawArg *string, functionName string, cache map[string]interface{}) (*FindReplaceFunctionArg, error) {
// rawArg is csv-encoded: "text to find","text to replace with"
if rawArg == nil {
return nil, fmt.Errorf("unexpected null argument to %s function", functionName)
}
// Check if we have it cached
v := cache[*rawArg]
if v != nil {
// fmt.Println("*** OK Got Cached value for", *rawArg,":",v)
return v.(*FindReplaceFunctionArg), nil
}
// Parsed the raw argument into FindReplaceFunctionArg and put it in the cache
rows, err := jcsv.Parse(*rawArg)
if len(rows)==0 || len(rows[0])!=2 || err != nil {
// It's not csv or there's no data
return nil, fmt.Errorf("error:no-data: argument %s cannot be parsed as csv: %v (%s function)", *rawArg, err, functionName)
}
results := &FindReplaceFunctionArg{
Find: rows[0][0],
ReplaceWith: rows[0][1],
}
cache[*rawArg] = results
return results, nil
}
func filterDigits(str string) string {
// Remove non digits characters
var buf strings.Builder
for _, c := range str {
if unicode.IsDigit(c) {
buf.WriteRune(c)
}
}
return buf.String()
}
func filterDouble(str string) string {
// clean up the amount
var buf strings.Builder
var c rune
for _, c = range str {
if c == '(' || c == '-' {
buf.WriteRune('-')
} else if unicode.IsDigit(c) || c == '.' {
buf.WriteRune(c)
}
}
return buf.String()
}
func (ri *ReteInputContext) applyCleasingFunction(reteSession *bridge.ReteSession, inputColumnSpec *ProcessMap,
inputValue *string, row []sql.NullString, inputColumnName2Pos map[string]int) (string, string) {
var obj, errMsg string
var err error
var sz int
switch inputColumnSpec.functionName.String {
case "trim":
obj = strings.TrimSpace(*inputValue)
case "validate_date":
_, err = reteSession.NewDateLiteral(*inputValue)
if err == nil {
obj = *inputValue
} else {
errMsg = err.Error()
}
case "to_upper":
obj = strings.ToUpper(*inputValue)
case "to_zip5":
// Remove non digits characters
inVal := filterDigits(*inputValue)
sz = len(inVal)
switch {
case sz == 0:
obj = ""
case sz < 5:
var v int
v, err = strconv.Atoi(inVal)
if err == nil {
obj = fmt.Sprintf("%05d", v)
if obj == "00000" {
obj = ""
}
} else {
errMsg = err.Error()
}
case sz == 5:
obj = inVal
if obj == "00000" {
obj = ""
}
case sz > 5 && sz < 9:
var v int
v, err = strconv.Atoi(inVal)
if err == nil {
obj = fmt.Sprintf("%09d", v)[:5]
if obj == "00000" {
obj = ""
}
} else {
errMsg = err.Error()
}
case sz == 9:
obj = inVal[:5]
if obj == "00000" {
obj = ""
}
default:
}
case "to_zipext4_from_zip9": // from a zip9 input
// Remove non digits characters
inVal := filterDigits(*inputValue)
sz = len(inVal)
switch {
case sz == 0:
obj = ""
case sz > 5 && sz < 9:
var v int
v, err = strconv.Atoi(inVal)
if err == nil {
obj = fmt.Sprintf("%09d", v)[5:]
if obj == "0000" {
obj = ""
}
} else {
errMsg = err.Error()
}
case sz == 9:
obj = inVal[5:]
if obj == "0000" {
obj = ""
}
default:
}
case "to_zipext4": // from a zip ext4 input
// Remove non digits characters
inVal := filterDigits(*inputValue)
sz = len(inVal)
switch {
case sz == 0:
obj = ""
case sz < 4:
var v int
v, err = strconv.Atoi(inVal)
if err == nil {
obj = fmt.Sprintf("%04d", v)
if obj == "0000" {
obj = ""
}
} else {
errMsg = err.Error()
}
case sz == 4:
obj = inVal
if obj == "0000" {
obj = ""
}
default:
}
case "format_phone": // Validate & format phone according to E.164
// Output: +1 area_code exchange_code subscriber_nbr
// area_code: 3 digits, 1st digit is not 0 or 1
// exchange_code: 3 digits, 1st digit is not 0 or 1
// subscriber_nbr: 4 digits
// Optional function argument is fmt.Sprintf formatter, expecting 3 string arguments (area_code, exchange_code, subscriber_nbr)
inVal := filterDigits(*inputValue)
if len(inVal) < 10 {
errMsg = "too few digits"
return obj, errMsg
}
if inVal[0] == '0' {
inVal = inVal[1:]
}
if inVal[0] == '1' {
inVal = inVal[1:]
}
if len(inVal) < 10 {
errMsg = "invalid sequence of digits"
return obj, errMsg
}
areaCode := inVal[0:3]
exchangeCode := inVal[3:6]
subscriberNbr := inVal[6:10]
if areaCode[0] == '0' || areaCode[0] == '1' {
errMsg = "invalid area code"
return obj, errMsg
}
if exchangeCode[0] == '0' || exchangeCode[0] == '1' {
errMsg = "invalid exchange code"
return obj, errMsg
}
arg := inputColumnSpec.argument.String
if len(arg) == 0 {
arg = "+1%s%s%s"
}
obj = fmt.Sprintf(arg, areaCode, exchangeCode, subscriberNbr)
case "reformat0":
if inputColumnSpec.argument.Valid {
// Remove non digits characters
inVal := filterDigits(*inputValue)
arg := inputColumnSpec.argument.String
var v int
if len(inVal) == 0 {
obj = ""
} else {
v, err = strconv.Atoi(inVal)
if err == nil {
obj = fmt.Sprintf(arg, v)
} else {
errMsg = err.Error()
}
}
} else {
// configuration error, bailing out
log.Panicf("ERROR missing argument for function reformat0 for input column: %s", inputColumnSpec.inputColumn.String)
}
case "overpunch_number":
if inputColumnSpec.argument.Valid {
// Get the number of decimal position
arg := inputColumnSpec.argument.String
var npos int
npos, err = strconv.Atoi(arg)
if err == nil {
obj, err = OverpunchNumber(*inputValue, npos)
if err != nil {
errMsg = err.Error()
}
} else {
errMsg = err.Error()
}
} else {
// configuration error, bailing out
log.Panicf("ERROR missing argument for function overpunch_number for input column: %s", inputColumnSpec.inputColumn.String)
}
case "apply_regex":
if inputColumnSpec.argument.Valid {
arg := inputColumnSpec.argument.String
re, ok := ri.reMap[arg]
if !ok {
re, err = regexp.Compile(arg)
if err != nil {
// configuration error, bailing out
log.Panicf("ERROR regex argument does not compile: %s", arg)
}
ri.reMap[arg] = re
}
obj = re.FindString(*inputValue)
} else {
// configuration error, bailing out
log.Panicf("ERROR missing argument for function apply_regex for input column: %s", inputColumnSpec.inputColumn.String)
}
case "scale_units":
if inputColumnSpec.argument.Valid {
arg := inputColumnSpec.argument.String
if arg == "1" {
obj = filterDouble(*inputValue)
} else {
divisor, ok := ri.argdMap[arg]
if !ok {
divisor, err = strconv.ParseFloat(arg, 64)
if err != nil {
// configuration error, bailing out
log.Panicf("ERROR divisor argument to function scale_units is not a double: %s", arg)
}
ri.argdMap[arg] = divisor
}
// Remove non digits characters
inVal := filterDouble(*inputValue)
var unit float64
unit, err = strconv.ParseFloat(inVal, 64)
if err == nil {
obj = fmt.Sprintf("%f", math.Ceil(unit/divisor))
} else {
errMsg = err.Error()
}
}
} else {
// configuration error, bailing out
log.Panicf("ERROR missing argument for function scale_units for input column: %s", inputColumnSpec.inputColumn.String)
}
case "parse_amount":
// clean up the amount
inVal := filterDouble(*inputValue)
if len(inVal) > 0 {
obj = inVal
// argument is optional, assume divisor is 1 if absent
if inputColumnSpec.argument.Valid {
arg := inputColumnSpec.argument.String
if arg != "1" {
divisor, ok := ri.argdMap[arg]
if !ok {
divisor, err = strconv.ParseFloat(arg, 64)
if err != nil {
// configuration error, bailing out
log.Panicf("ERROR divisor argument to function scale_units is not a double: %s", arg)
}
ri.argdMap[arg] = divisor
}
var amt float64
amt, err = strconv.ParseFloat(obj, 64)
if err == nil {
obj = fmt.Sprintf("%f", amt/divisor)
} else {
errMsg = err.Error()
}
}
}
}
case "concat", "concat_with":
// Cleansing function that concatenate input columns w delimiter
// Get the parsed argument
arg, err := ParseConcatFunctionArgument(&inputColumnSpec.argument.String, inputColumnSpec.functionName.String, inputColumnName2Pos, ri.parsedFunctionArguments)
if err != nil {
errMsg = err.Error()
} else {
var buf strings.Builder
buf.WriteString(*inputValue)
for i := range arg.ColumnPositions {
// fmt.Println("=== concat value @pos:",arg.ColumnPositions[i])
if row[arg.ColumnPositions[i]].Valid {
if arg.Delimit != "" {
buf.WriteString(arg.Delimit)
}
buf.WriteString(row[arg.ColumnPositions[i]].String)
}
}
obj = buf.String()
}
case "find_and_replace":
// Cleansing function that replace portion of the input column
// Get the parsed argument
arg, err := ParseFindReplaceFunctionArgument(&inputColumnSpec.argument.String, inputColumnSpec.functionName.String, ri.parsedFunctionArguments)
if err != nil {
errMsg = err.Error()
} else {
obj = strings.ReplaceAll(*inputValue, arg.Find, arg.ReplaceWith)
}
case "substring":
// Cleansing function that takes a substring of input columns
// Get the parsed argument
arg, err := ParseSubStringFunctionArgument(&inputColumnSpec.argument.String, inputColumnSpec.functionName.String, ri.parsedFunctionArguments)
if err != nil {
errMsg = err.Error()
} else {
end := arg.End
if end < 0 {
end = len(*inputValue) + end
}
if end > len(*inputValue) || end <= arg.Start {
obj = ""
} else {
obj = (*inputValue)[arg.Start:end]
}
}
default:
log.Panicf("ERROR unknown mapping function: %s", inputColumnSpec.functionName.String)
}
return obj, errMsg
}