forked from uswitch/bqshift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbqshift.go
84 lines (69 loc) · 2.12 KB
/
bqshift.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
package main
import (
"fmt"
"github.com/uswitch/bqshift/bigquery"
"github.com/uswitch/bqshift/redshift"
"github.com/uswitch/bqshift/storage"
"log"
)
type shifter struct {
redshift *redshift.Client
config *Configuration
}
func (s *shifter) Run(table string, partition *redshift.DatePartition, tableRef *bigquery.TableReference) error {
storageClient, err := storage.NewClient(tableRef, s.config.AWS.S3)
if err != nil {
return err
}
bq, err := bigquery.NewClient()
exists, err := bq.DatasetExists(tableRef.DatasetReference())
if err != nil {
return fmt.Errorf("error checking dataset: %s", err.Error())
}
if !exists {
return fmt.Errorf("dataset doesn't exist: %s", tableRef.DatasetID)
}
err = bq.EnsureTableExists(tableRef, s.config.DayPartition)
if err != nil {
return fmt.Errorf("error creating bigquery client: %s", err.Error())
}
log.Println("unloading to s3")
unloaded, err := s.redshift.Unload(table, partition, s.config.WhereClause)
if err != nil {
return fmt.Errorf("error unloading: %s", err.Error())
}
log.Println("transferring to cloud storage")
stored, err := storageClient.TransferToCloudStorage(unloaded)
if err != nil {
return fmt.Errorf("error transferring to cloud storage: %s", err.Error())
}
sourceSchema, err := s.redshift.ExtractSchema(table)
if err != nil {
return fmt.Errorf("error extracting source schema: %s", err.Error())
}
destSchema, err := sourceSchema.ToBigQuerySchema()
if err != nil {
return fmt.Errorf("error translating redshift schema to bigquery: %s", err.Error())
}
log.Println("loading into bigquery")
spec := &bigquery.LoadSpec{
Partitioned: s.config.DayPartition,
TableReference: tableRef,
BucketName: stored.BucketName,
ObjectPrefix: stored.Prefix,
Overwrite: s.config.OverwriteBigQuery,
Schema: destSchema,
}
err = bq.LoadTable(spec)
if err != nil {
return fmt.Errorf("error loading data into table: %s", err.Error())
}
return nil
}
func NewShifter(config *Configuration) (*shifter, error) {
client, err := redshift.NewClient(config.AWS)
if err != nil {
return nil, err
}
return &shifter{client, config}, nil
}