forked from mpchadwick/dbanon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
processor.go
110 lines (92 loc) · 2.4 KB
/
processor.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
package dbanon
import (
"strings"
"vitess.io/vitess/go/vt/sqlparser"
)
type LineProcessor struct {
Mode string
Config *Config
Provider ProviderInterface
Eav *Eav
}
func NewLineProcessor(m string, c *Config, p ProviderInterface, e *Eav) *LineProcessor {
return &LineProcessor{Mode: m, Config: c, Provider: p, Eav: e}
}
func (p LineProcessor) ProcessLine(s string) string {
i := strings.Index(s, "INSERT")
if i == 0 {
return p.processInsert(s)
}
findNextTable(s)
return s
}
func (p LineProcessor) processInsert(s string) string {
stmt, err := sqlparser.Parse(s)
if err != nil {
return s
}
insert, ok := stmt.(*sqlparser.Insert)
// This _shouldn't happen but the statement might not be an Insert
// For example, it'll be nil if the binary charset introducer is foudn
// https://github.com/blastrain/vitess-sqlparser/issues/25
if !ok {
return s
}
table := insert.Table.Name.String()
processor := p.Config.ProcessTable(table)
if processor == "" && p.Mode == "anonymize" {
return s
}
var attributeId string
var result bool
var dataType string
var entityTypeId string
rows := insert.Rows.(sqlparser.Values)
for _, vt := range rows {
for i, e := range vt {
column := currentTable[i].Name
if processor == "table" && p.Mode == "anonymize" {
result, dataType = p.Config.ProcessColumn(table, column)
if !result {
continue
}
}
switch v := e.(type) {
case *sqlparser.Literal:
if processor == "table" {
v.Val = p.Provider.Get(dataType, &v.Val)
} else {
if column == "attribute_id" {
attributeId = string(v.Val)
if p.Mode == "anonymize" {
result, dataType = p.Config.ProcessEav(table, attributeId)
}
}
if column == "value" && result {
v.Val = p.Provider.Get(dataType, &v.Val)
}
if p.Mode == "map-eav" {
if column == "entity_type_id" {
entityTypeId = string(v.Val)
}
if column == "entity_type_code" {
p.Eav.entityMap[string(v.Val)] = entityTypeId
}
if column == "attribute_code" {
for _, eavConfig := range p.Eav.Config.Eav {
if p.Eav.entityMap[eavConfig.Name] == entityTypeId {
for eavK, eavV := range eavConfig.Attributes {
if eavK == string(v.Val) {
eavConfig.Attributes[attributeId] = eavV
}
}
}
}
}
}
}
}
}
}
return sqlparser.String(insert) + ";\n"
}