/
abstract.go
228 lines (210 loc) · 7.62 KB
/
abstract.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
package sql
import (
"context"
"fmt"
bulker "github.com/jitsucom/bulker/bulkerlib"
"github.com/jitsucom/bulker/bulkerlib/types"
"github.com/jitsucom/bulker/jitsubase/logging"
"github.com/jitsucom/bulker/jitsubase/utils"
jsoniter "github.com/json-iterator/go"
"time"
)
// TODO: check whether COPY is transactional ?
// TODO: pk conflict on Redshift file storage ?
const unmappedDataColumn = "_unmapped_data"
type AbstractSQLStream struct {
id string
sqlAdapter SQLAdapter
mode bulker.BulkMode
options bulker.StreamOptions
tableName string
merge bool
mergeWindow int
omitNils bool
schemaFromOptions *Table
state bulker.State
inited bool
customTypes types.SQLTypes
pkColumns []string
timestampColumn string
startTime time.Time
}
func newAbstractStream(id string, p SQLAdapter, tableName string, mode bulker.BulkMode, streamOptions ...bulker.StreamOption) (*AbstractSQLStream, error) {
ps := AbstractSQLStream{id: id, sqlAdapter: p, tableName: tableName, mode: mode}
ps.options = bulker.StreamOptions{}
for _, option := range streamOptions {
ps.options.Add(option)
}
ps.merge = bulker.DeduplicateOption.Get(&ps.options)
pkColumns := bulker.PrimaryKeyOption.Get(&ps.options)
if ps.merge && len(pkColumns) == 0 {
return nil, fmt.Errorf("MergeRows option requires primary key in the destination table. Please provide WithPrimaryKey option")
}
if ps.merge {
ps.mergeWindow = DeduplicateWindow.Get(&ps.options)
}
var customFields = ColumnTypesOption.Get(&ps.options)
ps.pkColumns = pkColumns.ToSlice()
ps.timestampColumn = bulker.TimestampOption.Get(&ps.options)
ps.omitNils = OmitNilsOption.Get(&ps.options)
schema := bulker.SchemaOption.Get(&ps.options)
if !schema.IsEmpty() {
ps.schemaFromOptions = ps.sqlAdapter.TableHelper().MapSchema(ps.sqlAdapter, schema)
}
//TODO: max column?
ps.state = bulker.State{Status: bulker.Active}
ps.customTypes = customFields
ps.startTime = time.Now()
return &ps, nil
}
func (ps *AbstractSQLStream) preprocess(object types.Object) (*Table, types.Object, error) {
if ps.state.Status != bulker.Active {
return nil, nil, fmt.Errorf("stream is not active. Status: %s", ps.state.Status)
}
batchHeader, processedObject, err := ProcessEvents(ps.tableName, object, ps.customTypes, ps.omitNils, ps.sqlAdapter.StringifyObjects())
if err != nil {
return nil, nil, err
}
table, processedObject := ps.sqlAdapter.TableHelper().MapTableSchema(ps.sqlAdapter, batchHeader, processedObject, ps.pkColumns, ps.timestampColumn)
ps.state.ProcessedRows++
return table, processedObject, nil
}
func (ps *AbstractSQLStream) postConsume(err error) error {
if err != nil {
ps.state.ErrorRowIndex = ps.state.ProcessedRows
ps.state.SetError(err)
return err
} else {
ps.state.SuccessfulRows++
}
return nil
}
func (ps *AbstractSQLStream) postComplete(err error) (bulker.State, error) {
if err != nil {
ps.state.SetError(err)
ps.state.Status = bulker.Failed
} else {
ps.state.Status = bulker.Completed
}
return ps.state, err
}
func (ps *AbstractSQLStream) init(ctx context.Context) error {
if err := ps.sqlAdapter.Ping(ctx); err != nil {
return err
}
if ps.inited {
return nil
}
//setup required db object like 'schema' or 'dataset' if doesn't exist
err := ps.sqlAdapter.InitDatabase(ctx)
if err != nil {
return err
}
ps.inited = true
return nil
}
// adjustTableColumnTypes modify currentTable with extra new columns from desiredTable if such exists
// if some column already exists in the database, no problems if its DataType is castable to DataType of existing column
// if some new column is being added but with different DataTypes - type of this column will be changed to a common ancestor type
// object values that can't be casted will be added to '_unmaped_data' column of JSON type as an json object
// returns true if new column was added to the currentTable as a result of this function call
func (ps *AbstractSQLStream) adjustTableColumnTypes(currentTable, existingTable, desiredTable *Table, values types.Object) bool {
columnsAdded := false
current := currentTable.Columns
unmappedObj := map[string]any{}
for name, newCol := range desiredTable.Columns {
var existingCol types.SQLColumn
ok := false
if existingTable != nil {
existingCol, ok = existingTable.Columns[name]
}
if !ok {
existingCol, ok = current[name]
if !ok {
//column not exist in database - adding as New
newCol.New = true
current[name] = newCol
columnsAdded = true
continue
}
} else {
current[name] = existingCol
}
if existingCol.DataType == newCol.DataType {
continue
}
if newCol.Override {
//if column sql type is overridden by user - leave it this way
current[name] = newCol
continue
}
if !existingCol.New {
//column exists in database - check if its DataType is castable to DataType of existing column
v, ok := values[name]
if ok && v != nil {
if types.IsConvertible(newCol.DataType, existingCol.DataType) {
newVal, _, err := types.Convert(existingCol.DataType, v)
if err != nil {
//logging.Warnf("Can't convert '%s' value '%v' from %s to %s: %v", name, values[name], newCol.DataType.String(), existingCol.DataType.String(), err)
unmappedObj[name] = v
delete(values, name)
continue
} else {
//logging.Infof("Converted '%s' value '%v' from %s to %s: %v", name, values[name], newCol.DataType.String(), existingCol.DataType.String(), newVal)
values[name] = newVal
}
} else {
//logging.Warnf("Can't convert '%s' value '%v' from %s to %s", name, values[name], newCol.DataType.String(), existingCol.DataType.String())
unmappedObj[name] = v
delete(values, name)
continue
}
}
} else {
common := types.GetCommonAncestorType(existingCol.DataType, newCol.DataType)
if common != existingCol.DataType {
//logging.Warnf("Changed '%s' type from %s to %s because of %s", name, existingCol.DataType.String(), common.String(), newCol.DataType.String())
sqlType, ok := ps.sqlAdapter.GetSQLType(common)
if ok {
existingCol.DataType = common
existingCol.Type = sqlType
current[name] = existingCol
} else {
logging.SystemErrorf("Unknown column type %s mapping for %s", common, ps.sqlAdapter.Type())
}
}
}
}
if len(unmappedObj) > 0 {
jsonSQLType, _ := ps.sqlAdapter.GetSQLType(types.JSON)
added := utils.MapPutIfAbsent(current, ps.sqlAdapter.ColumnName(unmappedDataColumn), types.SQLColumn{DataType: types.JSON, Type: jsonSQLType})
columnsAdded = columnsAdded || added
if ps.sqlAdapter.StringifyObjects() {
b, _ := jsoniter.Marshal(unmappedObj)
values[ps.sqlAdapter.ColumnName(unmappedDataColumn)] = string(b)
} else {
values[ps.sqlAdapter.ColumnName(unmappedDataColumn)] = unmappedObj
}
}
return columnsAdded
}
func (ps *AbstractSQLStream) updateRepresentationTable(table *Table) {
if ps.state.Representation == nil ||
ps.state.Representation.(RepresentationTable).Name != table.Name ||
len(ps.state.Representation.(RepresentationTable).Schema) != len(table.Columns) {
ps.state.Representation = RepresentationTable{
Name: table.Name,
Schema: table.Columns.ToSimpleMap(),
PrimaryKeyFields: table.GetPKFields(),
PrimaryKeyName: table.PrimaryKeyName,
Temporary: table.Temporary,
}
}
}
type RepresentationTable struct {
Name string `json:"name"`
Schema map[string]string `json:"schema"`
PrimaryKeyFields []string `json:"primaryKeyFields,omitempty"`
PrimaryKeyName string `json:"primaryKeyName,omitempty"`
Temporary bool `json:"temporary,omitempty"`
}