-
Notifications
You must be signed in to change notification settings - Fork 307
/
redshift.go
1503 lines (1349 loc) · 44.4 KB
/
redshift.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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package redshift
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
"golang.org/x/exp/slices"
"github.com/lib/pq"
"github.com/tidwall/gjson"
"github.com/rudderlabs/rudder-go-kit/config"
"github.com/rudderlabs/rudder-go-kit/logger"
"github.com/rudderlabs/rudder-go-kit/stats"
"github.com/rudderlabs/rudder-server/services/filemanager"
"github.com/rudderlabs/rudder-server/utils/misc"
"github.com/rudderlabs/rudder-server/warehouse/client"
sqlmiddleware "github.com/rudderlabs/rudder-server/warehouse/integrations/middleware/sqlquerywrapper"
"github.com/rudderlabs/rudder-server/warehouse/internal/model"
"github.com/rudderlabs/rudder-server/warehouse/logfield"
"github.com/rudderlabs/rudder-server/warehouse/tunnelling"
warehouseutils "github.com/rudderlabs/rudder-server/warehouse/utils"
)
var errorsMappings = []model.JobError{
{
Type: model.AlterColumnError,
Format: regexp.MustCompile(`pq: cannot alter type of a column used by a view or rule`),
},
{
Type: model.InsufficientResourceError,
Format: regexp.MustCompile(`pq: Disk Full`),
},
{
Type: model.PermissionError,
Format: regexp.MustCompile(`redshift set query_group error : EOF`),
},
{
Type: model.ConcurrentQueriesError,
Format: regexp.MustCompile(`pq: 1023`),
},
{
Type: model.ColumnSizeError,
Format: regexp.MustCompile(`pq: Value too long for character type`),
},
{
Type: model.PermissionError,
Format: regexp.MustCompile(`pq: permission denied for database`),
},
{
Type: model.PermissionError,
Format: regexp.MustCompile(`pq: must be owner of relation`),
},
{
Type: model.ResourceNotFoundError,
Format: regexp.MustCompile(`pq: Cannot execute write query because system is in resize mode`),
},
{
Type: model.PermissionError,
Format: regexp.MustCompile(`pq: SSL is not enabled on the server`),
},
{
Type: model.ResourceNotFoundError,
Format: regexp.MustCompile(`Bucket .* not found`),
},
{
Type: model.ColumnCountError,
Format: regexp.MustCompile(`pq: tables can have at most 1600 columns`),
},
}
// String constants for redshift destination config
const (
RSHost = "host"
RSPort = "port"
RSDbName = "database"
RSUserName = "user"
RSPassword = "password"
)
const (
rudderStringLength = 512
provider = warehouseutils.RS
tableNameLimit = 127
)
var dataTypesMap = map[string]string{
"boolean": "boolean encode runlength",
"int": "bigint",
"bigint": "bigint",
"float": "double precision",
"string": "varchar(65535)",
"text": "varchar(65535)",
"datetime": "timestamp",
"json": "super",
}
var dataTypesMapToRudder = map[string]string{
"int": "int",
"int2": "int",
"int4": "int",
"int8": "int",
"bigint": "int",
"float": "float",
"float4": "float",
"float8": "float",
"numeric": "float",
"double precision": "float",
"boolean": "boolean",
"bool": "boolean",
"text": "string",
"character varying": "string",
"nchar": "string",
"bpchar": "string",
"character": "string",
"nvarchar": "string",
"string": "string",
"date": "datetime",
"timestamp without time zone": "datetime",
"timestamp with time zone": "datetime",
"super": "json",
}
var primaryKeyMap = map[string]string{
"users": "id",
"identifies": "id",
warehouseutils.DiscardsTable: "row_id",
}
var partitionKeyMap = map[string]string{
"users": "id",
"identifies": "id",
warehouseutils.DiscardsTable: "row_id, column_name, table_name",
}
type Redshift struct {
DB *sqlmiddleware.DB
Namespace string
Warehouse model.Warehouse
Uploader warehouseutils.Uploader
ConnectTimeout time.Duration
Logger logger.Logger
stats stats.Stats
SlowQueryThreshold time.Duration
DedupWindow bool
DedupWindowInHours time.Duration
SkipDedupDestinationIDs []string
SkipComputingUserLatestTraits bool
EnableDeleteByJobs bool
}
type S3ManifestEntryMetadata struct {
ContentLength int64 `json:"content_length"`
}
type S3ManifestEntry struct {
Url string `json:"url"`
Mandatory bool `json:"mandatory"`
Metadata S3ManifestEntryMetadata `json:"meta"`
}
type S3Manifest struct {
Entries []S3ManifestEntry `json:"entries"`
}
type RedshiftCredentials struct {
Host string
Port string
DbName string
Username string
Password string
timeout time.Duration
TunnelInfo *tunnelling.TunnelInfo
}
func New() *Redshift {
return &Redshift{
Logger: logger.NewLogger().Child("warehouse").Child("integrations").Child("redshift"),
stats: stats.Default,
}
}
func WithConfig(h *Redshift, config *config.Config) {
h.DedupWindow = config.GetBool("Warehouse.redshift.dedupWindow", false)
h.DedupWindowInHours = config.GetDuration("Warehouse.redshift.dedupWindowInHours", 720, time.Hour)
h.SkipDedupDestinationIDs = config.GetStringSlice("Warehouse.redshift.skipDedupDestinationIDs", nil)
h.SkipComputingUserLatestTraits = config.GetBool("Warehouse.redshift.skipComputingUserLatestTraits", false)
h.EnableDeleteByJobs = config.GetBool("Warehouse.redshift.enableDeleteByJobs", false)
h.SlowQueryThreshold = config.GetDuration("Warehouse.redshift.slowQueryThreshold", 5, time.Minute)
}
// getRSDataType gets datatype for rs which is mapped with RudderStack datatype
func getRSDataType(columnType string) string {
return dataTypesMap[columnType]
}
func ColumnsWithDataTypes(columns model.TableSchema, prefix string) string {
// TODO: do we need sorted order here?
var keys []string
for colName := range columns {
keys = append(keys, colName)
}
sort.Strings(keys)
var arr []string
for _, name := range keys {
arr = append(arr, fmt.Sprintf(`"%s%s" %s`, prefix, name, getRSDataType(columns[name])))
}
return strings.Join(arr, ",")
}
func (rs *Redshift) CreateTable(tableName string, columns model.TableSchema) (err error) {
name := fmt.Sprintf(`%q.%q`, rs.Namespace, tableName)
sortKeyField := "received_at"
if _, ok := columns["received_at"]; !ok {
sortKeyField = "uuid_ts"
if _, ok = columns["uuid_ts"]; !ok {
sortKeyField = "id"
}
}
var distKeySql string
if _, ok := columns["id"]; ok {
distKeySql = `DISTSTYLE KEY DISTKEY("id")`
}
sqlStatement := fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s ( %v ) %s SORTKEY(%q) `, name, ColumnsWithDataTypes(columns, ""), distKeySql, sortKeyField)
rs.Logger.Infof("Creating table in redshift for RS:%s : %v", rs.Warehouse.Destination.ID, sqlStatement)
_, err = rs.DB.Exec(sqlStatement)
return
}
func (rs *Redshift) DropTable(tableName string) (err error) {
sqlStatement := `DROP TABLE "%[1]s"."%[2]s"`
rs.Logger.Infof("RS: Dropping table in redshift for RS:%s : %v", rs.Warehouse.Destination.ID, sqlStatement)
_, err = rs.DB.Exec(fmt.Sprintf(sqlStatement, rs.Namespace, tableName))
return
}
func (rs *Redshift) schemaExists(_ string) (exists bool, err error) {
sqlStatement := fmt.Sprintf(`SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = '%s');`, rs.Namespace)
err = rs.DB.QueryRow(sqlStatement).Scan(&exists)
return
}
func (rs *Redshift) AddColumns(tableName string, columnsInfo []warehouseutils.ColumnInfo) error {
for _, columnInfo := range columnsInfo {
columnType := getRSDataType(columnInfo.Type)
query := fmt.Sprintf(`
ALTER TABLE
%q.%q
ADD
COLUMN %q %s;
`,
rs.Namespace,
tableName,
columnInfo.Name,
columnType,
)
rs.Logger.Infof("RS: Adding column for destinationID: %s, tableName: %s with query: %v", rs.Warehouse.Destination.ID, tableName, query)
if _, err := rs.DB.Exec(query); err != nil {
if CheckAndIgnoreColumnAlreadyExistError(err) {
rs.Logger.Infow("column already exists",
logfield.SourceID, rs.Warehouse.Source.ID,
logfield.SourceType, rs.Warehouse.Source.SourceDefinition.Name,
logfield.DestinationID, rs.Warehouse.Destination.ID,
logfield.DestinationType, rs.Warehouse.Destination.DestinationDefinition.Name,
logfield.WorkspaceID, rs.Warehouse.WorkspaceID,
logfield.Schema, rs.Namespace,
logfield.TableName, tableName,
logfield.ColumnName, columnInfo.Name,
logfield.ColumnType, columnType,
logfield.Error, err.Error(),
logfield.Query, query,
)
continue
}
return err
}
}
return nil
}
func CheckAndIgnoreColumnAlreadyExistError(err error) bool {
if err != nil {
if e, ok := err.(*pq.Error); ok {
if e.Code == "42701" {
return true
}
}
return false
}
return true
}
func (rs *Redshift) DeleteBy(tableNames []string, params warehouseutils.DeleteByParams) (err error) {
rs.Logger.Infof("RS: Cleaning up the following tables in redshift for RS:%s : %+v", tableNames, params)
rs.Logger.Infof("RS: Flag for enableDeleteByJobs is %t", rs.EnableDeleteByJobs)
for _, tb := range tableNames {
sqlStatement := fmt.Sprintf(`DELETE FROM "%[1]s"."%[2]s" WHERE
context_sources_job_run_id <> $1 AND
context_sources_task_run_id <> $2 AND
context_source_id = $3 AND
received_at < $4`,
rs.Namespace,
tb,
)
rs.Logger.Infof("RS: Deleting rows in table in redshift for RS:%s", rs.Warehouse.Destination.ID)
rs.Logger.Infof("RS: Executing the query %v", sqlStatement)
if rs.EnableDeleteByJobs {
_, err = rs.DB.Exec(sqlStatement,
params.JobRunId,
params.TaskRunId,
params.SourceId,
params.StartTime,
)
if err != nil {
rs.Logger.Errorf("Error in executing the query %s", err.Error())
return err
}
}
}
return nil
}
func (rs *Redshift) createSchema() (err error) {
sqlStatement := fmt.Sprintf(`CREATE SCHEMA IF NOT EXISTS %q`, rs.Namespace)
rs.Logger.Infof("Creating schema name in redshift for RS:%s : %v", rs.Warehouse.Destination.ID, sqlStatement)
_, err = rs.DB.Exec(sqlStatement)
return
}
func (rs *Redshift) generateManifest(ctx context.Context, tableName string) (string, error) {
loadFiles := rs.Uploader.GetLoadFilesMetadata(warehouseutils.GetLoadFilesOptions{Table: tableName})
loadFiles = warehouseutils.GetS3Locations(loadFiles)
var manifest S3Manifest
for idx, loadFile := range loadFiles {
manifestEntry := S3ManifestEntry{Url: loadFile.Location, Mandatory: true}
// add contentLength to manifest entry if it exists
contentLength := gjson.Get(string(loadFiles[idx].Metadata), "content_length")
if contentLength.Exists() {
manifestEntry.Metadata.ContentLength = contentLength.Int()
}
manifest.Entries = append(manifest.Entries, manifestEntry)
}
rs.Logger.Infof("RS: Generated manifest for table:%s", tableName)
manifestJSON, _ := json.Marshal(&manifest)
manifestFolder := misc.RudderRedshiftManifests
dirName := "/" + manifestFolder + "/"
tmpDirPath, err := misc.CreateTMPDIR()
if err != nil {
panic(err)
}
localManifestPath := fmt.Sprintf("%v%v", tmpDirPath+dirName, misc.FastUUID().String())
err = os.MkdirAll(filepath.Dir(localManifestPath), os.ModePerm)
if err != nil {
panic(err)
}
defer misc.RemoveFilePaths(localManifestPath)
_ = os.WriteFile(localManifestPath, manifestJSON, 0o644)
file, err := os.Open(localManifestPath)
if err != nil {
panic(err)
}
defer func() { _ = file.Close() }()
uploader, err := filemanager.DefaultFileManagerFactory.New(&filemanager.SettingsT{
Provider: warehouseutils.S3,
Config: misc.GetObjectStorageConfig(misc.ObjectStorageOptsT{
Provider: warehouseutils.S3,
Config: rs.Warehouse.Destination.Config,
UseRudderStorage: rs.Uploader.UseRudderStorage(),
WorkspaceID: rs.Warehouse.Destination.WorkspaceID,
}),
})
if err != nil {
return "", err
}
uploadOutput, err := uploader.Upload(ctx, file, manifestFolder, rs.Warehouse.Source.ID, rs.Warehouse.Destination.ID, time.Now().Format("01-02-2006"), tableName, misc.FastUUID().String())
if err != nil {
return "", err
}
return uploadOutput.Location, nil
}
func (rs *Redshift) dropStagingTables(stagingTableNames []string) {
for _, stagingTableName := range stagingTableNames {
rs.Logger.Infof("WH: dropping table %+v\n", stagingTableName)
_, err := rs.DB.Exec(fmt.Sprintf(`DROP TABLE "%[1]s"."%[2]s"`, rs.Namespace, stagingTableName))
if err != nil {
rs.Logger.Errorf("WH: RS: Error dropping staging tables in redshift: %v", err)
}
}
}
func (rs *Redshift) loadTable(ctx context.Context, tableName string, tableSchemaInUpload, tableSchemaAfterUpload model.TableSchema, skipTempTableDelete bool) (string, error) {
var (
err error
query string
stagingTableName string
rowsAffected int64
txn *sqlmiddleware.Tx
result sql.Result
)
rs.Logger.Infow("started loading",
logfield.SourceID, rs.Warehouse.Source.ID,
logfield.SourceType, rs.Warehouse.Source.SourceDefinition.Name,
logfield.DestinationID, rs.Warehouse.Destination.ID,
logfield.DestinationType, rs.Warehouse.Destination.DestinationDefinition.Name,
logfield.WorkspaceID, rs.Warehouse.WorkspaceID,
logfield.Namespace, rs.Namespace,
logfield.TableName, tableName,
)
manifestLocation, err := rs.generateManifest(ctx, tableName)
if err != nil {
return "", fmt.Errorf("generating manifest: %w", err)
}
rs.Logger.Infow("Generated manifest",
logfield.SourceID, rs.Warehouse.Source.ID,
logfield.SourceType, rs.Warehouse.Source.SourceDefinition.Name,
logfield.DestinationID, rs.Warehouse.Destination.ID,
logfield.DestinationType, rs.Warehouse.Destination.DestinationDefinition.Name,
logfield.WorkspaceID, rs.Warehouse.WorkspaceID,
logfield.Namespace, rs.Namespace,
logfield.TableName, tableName,
"manifestLocation", manifestLocation,
)
strKeys := warehouseutils.GetColumnsFromTableSchema(tableSchemaInUpload)
sort.Strings(strKeys)
sortedColumnNames := warehouseutils.JoinWithFormatting(strKeys, func(_ int, name string) string {
return fmt.Sprintf(`%q`, name)
}, ",")
stagingTableName = warehouseutils.StagingTableName(provider, tableName, tableNameLimit)
_, err = rs.DB.ExecContext(ctx, fmt.Sprintf(`CREATE TABLE %[1]q.%[2]q (LIKE %[1]q.%[3]q INCLUDING DEFAULTS);`,
rs.Namespace,
stagingTableName,
tableName,
))
if err != nil {
return "", fmt.Errorf("creating staging table: %w", err)
}
if !skipTempTableDelete {
defer rs.dropStagingTables([]string{stagingTableName})
}
manifestS3Location, region := warehouseutils.GetS3Location(manifestLocation)
if region == "" {
region = "us-east-1"
}
// create session token and temporary credentials
tempAccessKeyId, tempSecretAccessKey, token, err := warehouseutils.GetTemporaryS3Cred(&rs.Warehouse.Destination)
if err != nil {
rs.Logger.Warnw("getting temporary s3 credentials",
logfield.SourceID, rs.Warehouse.Source.ID,
logfield.SourceType, rs.Warehouse.Source.SourceDefinition.Name,
logfield.DestinationID, rs.Warehouse.Destination.ID,
logfield.DestinationType, rs.Warehouse.Destination.DestinationDefinition.Name,
logfield.WorkspaceID, rs.Warehouse.WorkspaceID,
logfield.Namespace, rs.Namespace,
logfield.TableName, tableName,
logfield.Error, err.Error(),
)
return "", fmt.Errorf("getting temporary s3 credentials: %w", err)
}
if txn, err = rs.DB.BeginTx(ctx, &sql.TxOptions{}); err != nil {
return "", fmt.Errorf("begin transaction: %w", err)
}
defer func() {
if err != nil {
_ = txn.Rollback()
}
}()
if rs.Uploader.GetLoadFileType() == warehouseutils.LOAD_FILE_TYPE_PARQUET {
query = fmt.Sprintf(`
COPY %v
FROM '%s'
ACCESS_KEY_ID '%s'
SECRET_ACCESS_KEY '%s'
SESSION_TOKEN '%s'
MANIFEST
FORMAT PARQUET;
`,
fmt.Sprintf(`%q.%q`, rs.Namespace, stagingTableName),
manifestS3Location,
tempAccessKeyId,
tempSecretAccessKey,
token,
)
} else {
query = fmt.Sprintf(`
COPY %v(%v)
FROM '%v'
CSV
GZIP
ACCESS_KEY_ID '%s'
SECRET_ACCESS_KEY '%s'
SESSION_TOKEN '%s'
REGION '%s'
DATEFORMAT 'auto'
TIMEFORMAT 'auto'
MANIFEST
TRUNCATECOLUMNS
EMPTYASNULL
BLANKSASNULL
FILLRECORD
ACCEPTANYDATE
TRIMBLANKS
ACCEPTINVCHARS
COMPUPDATE OFF
STATUPDATE OFF;
`,
fmt.Sprintf(`%q.%q`, rs.Namespace, stagingTableName),
sortedColumnNames,
manifestS3Location,
tempAccessKeyId,
tempSecretAccessKey,
token,
region,
)
}
sanitisedQuery, regexErr := misc.ReplaceMultiRegex(query, map[string]string{
"ACCESS_KEY_ID '[^']*'": "ACCESS_KEY_ID '***'",
"SECRET_ACCESS_KEY '[^']*'": "SECRET_ACCESS_KEY '***'",
"SESSION_TOKEN '[^']*'": "SESSION_TOKEN '***'",
})
if regexErr != nil {
sanitisedQuery = ""
}
rs.Logger.Infow("copy command",
logfield.SourceID, rs.Warehouse.Source.ID,
logfield.SourceType, rs.Warehouse.Source.SourceDefinition.Name,
logfield.DestinationID, rs.Warehouse.Destination.ID,
logfield.DestinationType, rs.Warehouse.Destination.DestinationDefinition.Name,
logfield.WorkspaceID, rs.Warehouse.WorkspaceID,
logfield.Namespace, rs.Namespace,
logfield.TableName, tableName,
logfield.Query, sanitisedQuery,
)
if _, err := txn.ExecContext(ctx, query); err != nil {
rs.Logger.Warnw("failure running copy command",
logfield.SourceID, rs.Warehouse.Source.ID,
logfield.SourceType, rs.Warehouse.Source.SourceDefinition.Name,
logfield.DestinationID, rs.Warehouse.Destination.ID,
logfield.DestinationType, rs.Warehouse.Destination.DestinationDefinition.Name,
logfield.WorkspaceID, rs.Warehouse.WorkspaceID,
logfield.Namespace, rs.Namespace,
logfield.TableName, tableName,
logfield.Query, sanitisedQuery,
logfield.Error, err.Error(),
)
return "", fmt.Errorf("running copy command: %w", normalizeError(err))
}
var (
primaryKey = "id"
partitionKey = "id"
)
if column, ok := primaryKeyMap[tableName]; ok {
primaryKey = column
}
if column, ok := partitionKeyMap[tableName]; ok {
partitionKey = column
}
// Deduplication
// Delete rows from the table which are already present in the staging table
query = fmt.Sprintf(`
DELETE FROM
%[1]s.%[2]q
USING
%[1]s.%[3]q _source
WHERE
_source.%[4]s = %[1]s.%[2]q.%[4]s
`,
rs.Namespace,
tableName,
stagingTableName,
primaryKey,
)
if rs.DedupWindow {
if _, ok := tableSchemaAfterUpload["received_at"]; ok {
query += fmt.Sprintf(`
AND %[1]s.%[2]q.received_at > GETDATE() - INTERVAL '%[3]d HOUR'
`,
rs.Namespace,
tableName,
rs.DedupWindowInHours/time.Hour,
)
}
}
if tableName == warehouseutils.DiscardsTable {
query += fmt.Sprintf(`
AND _source.%[3]s = %[1]s.%[2]q.%[3]s
AND _source.%[4]s = %[1]s.%[2]q.%[4]s
`,
rs.Namespace,
tableName,
"table_name",
"column_name",
)
}
if !slices.Contains(rs.SkipDedupDestinationIDs, rs.Warehouse.Destination.ID) {
rs.Logger.Infow("deduplication",
logfield.SourceID, rs.Warehouse.Source.ID,
logfield.SourceType, rs.Warehouse.Source.SourceDefinition.Name,
logfield.DestinationID, rs.Warehouse.Destination.ID,
logfield.DestinationType, rs.Warehouse.Destination.DestinationDefinition.Name,
logfield.WorkspaceID, rs.Warehouse.WorkspaceID,
logfield.Namespace, rs.Namespace,
logfield.TableName, tableName,
logfield.Query, query,
)
if result, err = txn.ExecContext(ctx, query); err != nil {
rs.Logger.Warnw("deleting from original table for dedup",
logfield.SourceID, rs.Warehouse.Source.ID,
logfield.SourceType, rs.Warehouse.Source.SourceDefinition.Name,
logfield.DestinationID, rs.Warehouse.Destination.ID,
logfield.DestinationType, rs.Warehouse.Destination.DestinationDefinition.Name,
logfield.WorkspaceID, rs.Warehouse.WorkspaceID,
logfield.Namespace, rs.Namespace,
logfield.TableName, tableName,
logfield.Query, query,
logfield.Error, err.Error(),
)
return "", fmt.Errorf("deleting from original table for dedup: %w", normalizeError(err))
}
if rowsAffected, err = result.RowsAffected(); err != nil {
rs.Logger.Warnw("getting rows affected for dedup",
logfield.SourceID, rs.Warehouse.Source.ID,
logfield.SourceType, rs.Warehouse.Source.SourceDefinition.Name,
logfield.DestinationID, rs.Warehouse.Destination.ID,
logfield.DestinationType, rs.Warehouse.Destination.DestinationDefinition.Name,
logfield.WorkspaceID, rs.Warehouse.WorkspaceID,
logfield.Namespace, rs.Namespace,
logfield.TableName, tableName,
logfield.Query, query,
logfield.Error, err.Error(),
)
return "", fmt.Errorf("getting rows affected for dedup: %w", err)
}
rs.stats.NewTaggedStat("dedup_rows", stats.CountType, stats.Tags{
"sourceID": rs.Warehouse.Source.ID,
"sourceType": rs.Warehouse.Source.SourceDefinition.Name,
"destID": rs.Warehouse.Destination.ID,
"destType": rs.Warehouse.Destination.DestinationDefinition.Name,
"workspaceId": rs.Warehouse.WorkspaceID,
"namespace": rs.Namespace,
"tableName": tableName,
}).Count(int(rowsAffected))
}
// Deduplication
// Insert rows from staging table to the original table
quotedColumnNames := warehouseutils.DoubleQuoteAndJoinByComma(strKeys)
query = fmt.Sprintf(`
INSERT INTO %[1]q.%[2]q (%[3]s)
SELECT
%[3]s
FROM
(
SELECT
*,
row_number() OVER (
PARTITION BY %[5]s
ORDER BY
received_at ASC
) AS _rudder_staging_row_number
FROM
%[1]q.%[4]q
) AS _
WHERE
_rudder_staging_row_number = 1;
`,
rs.Namespace,
tableName,
quotedColumnNames,
stagingTableName,
partitionKey,
)
rs.Logger.Infow("inserting into original table",
logfield.SourceID, rs.Warehouse.Source.ID,
logfield.SourceType, rs.Warehouse.Source.SourceDefinition.Name,
logfield.DestinationID, rs.Warehouse.Destination.ID,
logfield.DestinationType, rs.Warehouse.Destination.DestinationDefinition.Name,
logfield.WorkspaceID, rs.Warehouse.WorkspaceID,
logfield.Namespace, rs.Namespace,
logfield.TableName, tableName,
logfield.Query, query,
)
if _, err = txn.ExecContext(ctx, query); err != nil {
rs.Logger.Warnw("failed inserting into original table",
logfield.SourceID, rs.Warehouse.Source.ID,
logfield.SourceType, rs.Warehouse.Source.SourceDefinition.Name,
logfield.DestinationID, rs.Warehouse.Destination.ID,
logfield.DestinationType, rs.Warehouse.Destination.DestinationDefinition.Name,
logfield.WorkspaceID, rs.Warehouse.WorkspaceID,
logfield.Namespace, rs.Namespace,
logfield.TableName, tableName,
logfield.Error, err.Error(),
)
return "", fmt.Errorf("inserting into original table: %w", normalizeError(err))
}
if err = txn.Commit(); err != nil {
rs.Logger.Warnw("committing transaction",
logfield.SourceID, rs.Warehouse.Source.ID,
logfield.SourceType, rs.Warehouse.Source.SourceDefinition.Name,
logfield.DestinationID, rs.Warehouse.Destination.ID,
logfield.DestinationType, rs.Warehouse.Destination.DestinationDefinition.Name,
logfield.WorkspaceID, rs.Warehouse.WorkspaceID,
logfield.Namespace, rs.Namespace,
logfield.TableName, tableName,
logfield.Error, err.Error(),
)
return "", fmt.Errorf("committing transaction: %w", err)
}
rs.Logger.Infow("completed loading",
logfield.SourceID, rs.Warehouse.Source.ID,
logfield.SourceType, rs.Warehouse.Source.SourceDefinition.Name,
logfield.DestinationID, rs.Warehouse.Destination.ID,
logfield.DestinationType, rs.Warehouse.Destination.DestinationDefinition.Name,
logfield.WorkspaceID, rs.Warehouse.WorkspaceID,
logfield.Namespace, rs.Namespace,
logfield.TableName, tableName,
)
return stagingTableName, nil
}
func (rs *Redshift) loadUserTables(ctx context.Context) map[string]error {
var (
err error
query string
identifyStagingTable string
txn *sqlmiddleware.Tx
userColNames []string
firstValProps []string
)
rs.Logger.Infow("started loading for identifies and users tables",
logfield.SourceID, rs.Warehouse.Source.ID,
logfield.SourceType, rs.Warehouse.Source.SourceDefinition.Name,
logfield.DestinationID, rs.Warehouse.Destination.ID,
logfield.DestinationType, rs.Warehouse.Destination.DestinationDefinition.Name,
logfield.WorkspaceID, rs.Warehouse.WorkspaceID,
logfield.Namespace, rs.Namespace,
)
identifyStagingTable, err = rs.loadTable(ctx, warehouseutils.IdentifiesTable, rs.Uploader.GetTableSchemaInUpload(warehouseutils.IdentifiesTable), rs.Uploader.GetTableSchemaInWarehouse(warehouseutils.IdentifiesTable), true)
if err != nil {
return map[string]error{
warehouseutils.IdentifiesTable: fmt.Errorf("loading identifies table: %w", err),
}
}
defer rs.dropStagingTables([]string{identifyStagingTable})
if len(rs.Uploader.GetTableSchemaInUpload(warehouseutils.UsersTable)) == 0 {
return map[string]error{
warehouseutils.IdentifiesTable: nil,
}
}
if rs.SkipComputingUserLatestTraits {
_, err := rs.loadTable(ctx, warehouseutils.UsersTable, rs.Uploader.GetTableSchemaInUpload(warehouseutils.UsersTable), rs.Uploader.GetTableSchemaInWarehouse(warehouseutils.UsersTable), false)
if err != nil {
return map[string]error{
warehouseutils.IdentifiesTable: nil,
warehouseutils.UsersTable: fmt.Errorf("loading users table: %w", err),
}
}
return map[string]error{
warehouseutils.IdentifiesTable: nil,
warehouseutils.UsersTable: nil,
}
}
userColMap := rs.Uploader.GetTableSchemaInWarehouse(warehouseutils.UsersTable)
for colName := range userColMap {
// do not reference uuid in queries as it can be an autoincrement field set by segment compatible tables
if colName == "id" || colName == "user_id" || colName == "uuid" {
continue
}
userColNames = append(userColNames, colName)
firstValProps = append(firstValProps, fmt.Sprintf(`FIRST_VALUE("%[1]s" IGNORE NULLS) OVER (PARTITION BY id ORDER BY received_at DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS "%[1]s"`, colName))
}
quotedUserColNames := warehouseutils.DoubleQuoteAndJoinByComma(userColNames)
stagingTableName := warehouseutils.StagingTableName(provider, warehouseutils.UsersTable, tableNameLimit)
query = fmt.Sprintf(`
CREATE TABLE %[1]q.%[2]q AS (
SELECT
DISTINCT *
FROM
(
SELECT
id,
%[3]s
FROM
(
(
SELECT
id,
%[6]s
FROM
%[1]q.%[4]q
WHERE
id in (
SELECT
DISTINCT(user_id)
FROM
%[1]q.%[5]q
WHERE
user_id IS NOT NULL
)
)
UNION
(
SELECT
user_id,
%[6]s
FROM
%[1]q.%[5]q
WHERE
user_id IS NOT NULL
)
)
)
);
`,
rs.Namespace,
stagingTableName,
strings.Join(firstValProps, ","),
warehouseutils.UsersTable,
identifyStagingTable,
quotedUserColNames,
)
if txn, err = rs.DB.BeginTx(ctx, &sql.TxOptions{}); err != nil {
return map[string]error{
warehouseutils.IdentifiesTable: fmt.Errorf("beginning transaction: %w", err),
}
}
if _, err = txn.ExecContext(ctx, query); err != nil {
_ = txn.Rollback()
rs.Logger.Warnw("creating staging table for users",
logfield.SourceID, rs.Warehouse.Source.ID,
logfield.SourceType, rs.Warehouse.Source.SourceDefinition.Name,
logfield.DestinationID, rs.Warehouse.Destination.ID,
logfield.DestinationType, rs.Warehouse.Destination.DestinationDefinition.Name,
logfield.WorkspaceID, rs.Warehouse.WorkspaceID,
logfield.Namespace, rs.Namespace,
logfield.TableName, warehouseutils.UsersTable,
logfield.Error, err.Error(),
)
return map[string]error{
warehouseutils.IdentifiesTable: nil,
warehouseutils.UsersTable: fmt.Errorf("creating staging table for users: %w", err),
}
}
defer rs.dropStagingTables([]string{stagingTableName})
primaryKey := "id"
query = fmt.Sprintf(`
DELETE FROM
%[1]s.%[2]q USING %[1]s.%[3]q _source
WHERE
(
_source.%[4]s = %[1]s.%[2]s.%[4]s
);
`,
rs.Namespace,
warehouseutils.UsersTable,
stagingTableName,
primaryKey,
)
if _, err = txn.ExecContext(ctx, query); err != nil {
_ = txn.Rollback()
rs.Logger.Warnw("deleting from users table for dedup",
logfield.SourceID, rs.Warehouse.Source.ID,
logfield.SourceType, rs.Warehouse.Source.SourceDefinition.Name,
logfield.DestinationID, rs.Warehouse.Destination.ID,
logfield.DestinationType, rs.Warehouse.Destination.DestinationDefinition.Name,
logfield.WorkspaceID, rs.Warehouse.WorkspaceID,
logfield.Namespace, rs.Namespace,
logfield.Query, query,
logfield.TableName, warehouseutils.UsersTable,
logfield.Error, err.Error(),
)
return map[string]error{
warehouseutils.UsersTable: fmt.Errorf("deleting from original table for dedup: %w", normalizeError(err)),
}
}
query = fmt.Sprintf(`
INSERT INTO %[1]q.%[2]q (%[4]s)
SELECT
%[4]s
FROM
%[1]q.%[3]q;
`,
rs.Namespace,
warehouseutils.UsersTable,
stagingTableName,
warehouseutils.DoubleQuoteAndJoinByComma(append([]string{"id"}, userColNames...)),
)
rs.Logger.Infow("inserting into users table",
logfield.SourceID, rs.Warehouse.Source.ID,
logfield.SourceType, rs.Warehouse.Source.SourceDefinition.Name,
logfield.DestinationID, rs.Warehouse.Destination.ID,
logfield.DestinationType, rs.Warehouse.Destination.DestinationDefinition.Name,
logfield.WorkspaceID, rs.Warehouse.WorkspaceID,
logfield.Namespace, rs.Namespace,
logfield.TableName, warehouseutils.UsersTable,
logfield.Query, query,
)
if _, err = txn.ExecContext(ctx, query); err != nil {
_ = txn.Rollback()
rs.Logger.Warnw("failed inserting into users table",
logfield.SourceID, rs.Warehouse.Source.ID,
logfield.SourceType, rs.Warehouse.Source.SourceDefinition.Name,
logfield.DestinationID, rs.Warehouse.Destination.ID,
logfield.DestinationType, rs.Warehouse.Destination.DestinationDefinition.Name,
logfield.WorkspaceID, rs.Warehouse.WorkspaceID,
logfield.Namespace, rs.Namespace,
logfield.TableName, warehouseutils.UsersTable,
logfield.Error, err.Error(),
)
return map[string]error{
warehouseutils.IdentifiesTable: nil,
warehouseutils.UsersTable: fmt.Errorf("inserting into users table from staging table: %w", normalizeError(err)),
}
}
if err = txn.Commit(); err != nil {
_ = txn.Rollback()
rs.Logger.Warnw("committing transaction for user table",
logfield.SourceID, rs.Warehouse.Source.ID,
logfield.SourceType, rs.Warehouse.Source.SourceDefinition.Name,
logfield.DestinationID, rs.Warehouse.Destination.ID,
logfield.DestinationType, rs.Warehouse.Destination.DestinationDefinition.Name,
logfield.WorkspaceID, rs.Warehouse.WorkspaceID,
logfield.Namespace, rs.Namespace,
logfield.TableName, warehouseutils.UsersTable,
logfield.Error, err.Error(),
)