-
Notifications
You must be signed in to change notification settings - Fork 316
/
schema.go
382 lines (341 loc) · 12.6 KB
/
schema.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
package warehouse
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"reflect"
"github.com/rudderlabs/rudder-server/warehouse/internal/repo"
"golang.org/x/exp/slices"
"github.com/rudderlabs/rudder-server/utils/misc"
"github.com/rudderlabs/rudder-server/warehouse/integrations/manager"
"github.com/rudderlabs/rudder-server/warehouse/internal/model"
"github.com/rudderlabs/rudder-server/warehouse/logfield"
warehouseutils "github.com/rudderlabs/rudder-server/warehouse/utils"
)
type SchemaHandle struct {
dbHandle *sql.DB
stagingFiles []*model.StagingFile
warehouse model.Warehouse
localSchema model.Schema
schemaInWarehouse model.Schema
unrecognizedSchemaInWarehouse model.Schema
uploadSchema model.Schema
whSchemaRepo *repo.WHSchema
}
func HandleSchemaChange(existingDataType, currentDataType model.SchemaType, value any) (any, error) {
var (
newColumnVal any
err error
)
if existingDataType == model.StringDataType || existingDataType == model.TextDataType {
// only stringify if the previous type is non-string/text/json
if currentDataType != model.StringDataType && currentDataType != model.TextDataType && currentDataType != model.JSONDataType {
newColumnVal = fmt.Sprintf("%v", value)
} else {
newColumnVal = value
}
} else if (currentDataType == model.IntDataType || currentDataType == model.BigIntDataType) && existingDataType == model.FloatDataType {
intVal, ok := value.(int)
if !ok {
err = ErrIncompatibleSchemaConversion
} else {
newColumnVal = float64(intVal)
}
} else if currentDataType == model.FloatDataType && (existingDataType == model.IntDataType || existingDataType == model.BigIntDataType) {
floatVal, ok := value.(float64)
if !ok {
err = ErrIncompatibleSchemaConversion
} else {
newColumnVal = int(floatVal)
}
} else if existingDataType == model.JSONDataType {
var interfaceSliceSample []any
if currentDataType == model.IntDataType || currentDataType == model.FloatDataType || currentDataType == model.BooleanDataType {
newColumnVal = fmt.Sprintf("%v", value)
} else if reflect.TypeOf(value) == reflect.TypeOf(interfaceSliceSample) {
newColumnVal = value
} else {
newColumnVal = fmt.Sprintf(`"%v"`, value)
}
} else {
err = ErrSchemaConversionNotSupported
}
return newColumnVal, err
}
func (sh *SchemaHandle) getLocalSchema() (model.Schema, error) {
whSchema, err := sh.whSchemaRepo.GetForNamespace(
context.TODO(),
sh.warehouse.Source.ID,
sh.warehouse.Destination.ID,
sh.warehouse.Namespace,
)
if err != nil {
return nil, fmt.Errorf("get schema for namespace: %w", err)
}
if whSchema.Schema == nil {
return model.Schema{}, nil
}
return whSchema.Schema, nil
}
func (sh *SchemaHandle) updateLocalSchema(uploadId int64, updatedSchema model.Schema) error {
_, err := sh.whSchemaRepo.Insert(context.TODO(), &model.WHSchema{
UploadID: uploadId,
SourceID: sh.warehouse.Source.ID,
Namespace: sh.warehouse.Namespace,
DestinationID: sh.warehouse.Destination.ID,
DestinationType: sh.warehouse.Type,
Schema: updatedSchema,
})
return err
}
func (sh *SchemaHandle) fetchSchemaFromWarehouse(whManager manager.Manager) (schemaInWarehouse, unrecognizedSchemaInWarehouse model.Schema, err error) {
schemaInWarehouse, unrecognizedSchemaInWarehouse, err = whManager.FetchSchema()
if err != nil {
pkgLogger.Errorf(`[WH]: Failed fetching schema from warehouse: %v`, err)
return model.Schema{}, model.Schema{}, err
}
sh.SkipDeprecatedColumns(schemaInWarehouse)
sh.SkipDeprecatedColumns(unrecognizedSchemaInWarehouse)
return schemaInWarehouse, unrecognizedSchemaInWarehouse, nil
}
func (sh *SchemaHandle) SkipDeprecatedColumns(schema model.Schema) {
for tableName, columnMap := range schema {
for columnName := range columnMap {
if warehouseutils.DeprecatedColumnsRegex.MatchString(columnName) {
pkgLogger.Debugw("skipping deprecated column",
logfield.SourceID, sh.warehouse.Source.ID,
logfield.DestinationID, sh.warehouse.Destination.ID,
logfield.DestinationType, sh.warehouse.Destination.DestinationDefinition.Name,
logfield.WorkspaceID, sh.warehouse.WorkspaceID,
logfield.Namespace, sh.warehouse.Namespace,
logfield.TableName, tableName,
logfield.ColumnName, columnName,
)
delete(schema[tableName], columnName)
continue
}
}
}
}
func MergeSchema(currentSchema model.Schema, schemaList []model.Schema, currentMergedSchema model.Schema, warehouseType string) model.Schema {
if len(currentMergedSchema) == 0 {
currentMergedSchema = model.Schema{}
}
setColumnTypeFromExistingSchema := func(refSchema model.Schema, tableName, refTableName, columnName, refColumnName, columnType string) bool {
columnTypeInDB, ok := refSchema[refTableName][refColumnName]
if !ok {
return false
}
if columnTypeInDB == "string" && columnType == "text" {
currentMergedSchema[tableName][columnName] = columnType
return true
}
// if columnTypeInDB is text, then we should not change it to string
if currentMergedSchema[tableName][columnName] == "text" {
return true
}
currentMergedSchema[tableName][columnName] = columnTypeInDB
return true
}
usersTableName := warehouseutils.ToProviderCase(warehouseType, "users")
identifiesTableName := warehouseutils.ToProviderCase(warehouseType, "identifies")
for _, schema := range schemaList {
for tableName, columnMap := range schema {
if currentMergedSchema[tableName] == nil {
currentMergedSchema[tableName] = make(model.TableSchema)
}
var toInferFromIdentifies bool
var refSchema model.Schema
if tableName == usersTableName {
if _, ok := currentSchema[identifiesTableName]; ok {
toInferFromIdentifies = true
refSchema = currentSchema
} else if _, ok := currentMergedSchema[identifiesTableName]; ok { // also check in identifies of currentMergedSchema if identifies table not present in warehouse
toInferFromIdentifies = true
refSchema = currentMergedSchema
}
}
for columnName, columnType := range columnMap {
// if column already has a type in db, use that
// check for data type in identifies for users table before check in users table
// to ensure same data type is set for the same column in both users and identifies
if tableName == usersTableName && toInferFromIdentifies {
refColumnName := columnName
if columnName == warehouseutils.ToProviderCase(warehouseType, "id") {
refColumnName = warehouseutils.ToProviderCase(warehouseType, "user_id")
}
if setColumnTypeFromExistingSchema(refSchema, tableName, identifiesTableName, columnName, refColumnName, columnType) {
continue
}
}
if _, ok := currentSchema[tableName]; ok {
if setColumnTypeFromExistingSchema(currentSchema, tableName, tableName, columnName, columnName, columnType) {
continue
}
}
// check if we already set the columnType in currentMergedSchema
if _, ok := currentMergedSchema[tableName][columnName]; !ok {
currentMergedSchema[tableName][columnName] = columnType
}
}
}
}
return currentMergedSchema
}
func (sh *SchemaHandle) safeName(columnName string) string {
return warehouseutils.ToProviderCase(sh.warehouse.Type, columnName)
}
func (sh *SchemaHandle) getDiscardsSchema() model.TableSchema {
discards := model.TableSchema{}
for colName, colType := range warehouseutils.DiscardsSchema {
discards[sh.safeName(colName)] = colType
}
// add loaded_at for bq to be segment compatible
if sh.warehouse.Type == warehouseutils.BQ {
discards[sh.safeName("loaded_at")] = "datetime"
}
return discards
}
func (sh *SchemaHandle) getMergeRulesSchema() model.TableSchema {
return model.TableSchema{
sh.safeName("merge_property_1_type"): "string",
sh.safeName("merge_property_1_value"): "string",
sh.safeName("merge_property_2_type"): "string",
sh.safeName("merge_property_2_value"): "string",
}
}
func (sh *SchemaHandle) getIdentitiesMappingsSchema() model.TableSchema {
return model.TableSchema{
sh.safeName("merge_property_type"): "string",
sh.safeName("merge_property_value"): "string",
sh.safeName("rudder_id"): "string",
sh.safeName("updated_at"): "datetime",
}
}
func (sh *SchemaHandle) isIDResolutionEnabled() bool {
return warehouseutils.IDResolutionEnabled() && slices.Contains(warehouseutils.IdentityEnabledWarehouses, sh.warehouse.Type)
}
func (sh *SchemaHandle) consolidateStagingFilesSchemaUsingWarehouseSchema() model.Schema {
schemaInLocalDB := sh.localSchema
consolidatedSchema := model.Schema{}
count := 0
for {
lastIndex := count + stagingFilesSchemaPaginationSize
if lastIndex >= len(sh.stagingFiles) {
lastIndex = len(sh.stagingFiles)
}
var ids []int64
for _, stagingFile := range sh.stagingFiles[count:lastIndex] {
ids = append(ids, stagingFile.ID)
}
sqlStatement := fmt.Sprintf(`
SELECT
schema
FROM
%s
WHERE
id IN (%s);
`,
warehouseutils.WarehouseStagingFilesTable,
misc.IntArrayToString(ids, ","),
)
rows, err := sh.dbHandle.Query(sqlStatement)
if err != nil && err != sql.ErrNoRows {
panic(fmt.Errorf("Query: %s\nfailed with Error : %w", sqlStatement, err))
}
var schemas []model.Schema
for rows.Next() {
var s json.RawMessage
err := rows.Scan(&s)
if err != nil {
panic(fmt.Errorf("Failed to scan result from query: %s\nwith Error : %w", sqlStatement, err))
}
var schema model.Schema
err = json.Unmarshal(s, &schema)
if err != nil {
panic(fmt.Errorf("unmarshalling: %s failed with Error : %w", string(s), err))
}
schemas = append(schemas, schema)
}
_ = rows.Close()
consolidatedSchema = MergeSchema(schemaInLocalDB, schemas, consolidatedSchema, sh.warehouse.Type)
count += stagingFilesSchemaPaginationSize
if count >= len(sh.stagingFiles) {
break
}
}
// add rudder_discards Schema
consolidatedSchema[sh.safeName(warehouseutils.DiscardsTable)] = sh.getDiscardsSchema()
// add rudder_identity_mappings Schema
if sh.isIDResolutionEnabled() {
if _, ok := consolidatedSchema[sh.safeName(warehouseutils.IdentityMergeRulesTable)]; ok {
consolidatedSchema[sh.safeName(warehouseutils.IdentityMergeRulesTable)] = sh.getMergeRulesSchema()
consolidatedSchema[sh.safeName(warehouseutils.IdentityMappingsTable)] = sh.getIdentitiesMappingsSchema()
}
}
return consolidatedSchema
}
// hasSchemaChanged Default behaviour is to do the deep equals.
// If we are skipping deep equals, then we are validating local schemas against warehouse schemas only.
// Not the other way around.
func hasSchemaChanged(localSchema, schemaInWarehouse model.Schema) bool {
if !skipDeepEqualSchemas {
eq := reflect.DeepEqual(localSchema, schemaInWarehouse)
return !eq
}
// Iterating through all tableName in the localSchema
for tableName := range localSchema {
localColumns := localSchema[tableName]
warehouseColumns, whColumnsExist := schemaInWarehouse[tableName]
// If warehouse does not contain the specified table return true.
if !whColumnsExist {
return true
}
for columnName := range localColumns {
localColumn := localColumns[columnName]
warehouseColumn := warehouseColumns[columnName]
// If warehouse does not contain the specified column return true.
// If warehouse column does not match with the local one return true
if localColumn != warehouseColumn {
return true
}
}
}
return false
}
func getTableSchemaDiff(tableName string, currentSchema, uploadSchema model.Schema) (diff warehouseutils.TableSchemaDiff) {
diff = warehouseutils.TableSchemaDiff{
ColumnMap: make(model.TableSchema),
UpdatedSchema: make(model.TableSchema),
AlteredColumnMap: make(model.TableSchema),
}
var currentTableSchema model.TableSchema
var ok bool
if currentTableSchema, ok = currentSchema[tableName]; !ok {
if _, ok := uploadSchema[tableName]; !ok {
return
}
diff.Exists = true
diff.TableToBeCreated = true
diff.ColumnMap = uploadSchema[tableName]
diff.UpdatedSchema = uploadSchema[tableName]
return diff
}
for columnName, columnType := range currentSchema[tableName] {
diff.UpdatedSchema[columnName] = columnType
}
diff.ColumnMap = make(model.TableSchema)
for columnName, columnType := range uploadSchema[tableName] {
if _, ok := currentTableSchema[columnName]; !ok {
diff.ColumnMap[columnName] = columnType
diff.UpdatedSchema[columnName] = columnType
diff.Exists = true
} else if columnType == "text" && currentTableSchema[columnName] == "string" {
diff.AlteredColumnMap[columnName] = columnType
diff.UpdatedSchema[columnName] = columnType
diff.Exists = true
}
}
return diff
}