-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunction.go
96 lines (82 loc) · 2.04 KB
/
function.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
package function
import (
"context"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"cloud.google.com/go/bigquery"
"google.golang.org/api/firestore/v1"
"google.golang.org/api/option"
)
var projectID string
var dataset string
var table string
func init() {
projectID = os.Getenv("PROJECT_ID")
dataset = os.Getenv("BQ_DATASET")
table = os.Getenv("BQ_TABLE")
}
func ExportFirestoreToGCS(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
svc, err := firestore.NewService(ctx, option.WithScopes(firestore.DatastoreScope, firestore.CloudPlatformScope))
if err != nil {
log.Printf("error: %s", err)
w.WriteHeader(500)
return
}
req := &firestore.GoogleFirestoreAdminV1ExportDocumentsRequest{
OutputUriPrefix: gsPrefix(projectID),
}
_, err = firestore.NewProjectsDatabasesService(svc).ExportDocuments(
savePath(projectID),
req,
).Context(ctx).Do()
if err != nil {
log.Printf("error: %s", err)
w.WriteHeader(500)
return
}
log.Println("backup successfully")
}
func LoadOnBigQuery(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
c, err := bigquery.NewClient(ctx, projectID)
if err != nil {
log.Printf("error: %s", err)
w.WriteHeader(500)
return
}
prefix := gsPrefix(projectID)
savePath := savePath(projectID)
path := filepath.Join(prefix, savePath)
gcsRef := bigquery.NewGCSReference(path)
gcsRef.AllowJaggedRows = true
myDataset := c.Dataset(dataset)
loader := myDataset.Table(table).LoaderFrom(gcsRef)
loader.CreateDisposition = bigquery.CreateNever
job, err := loader.Run(ctx)
if err != nil {
log.Printf("error: %s", err)
w.WriteHeader(500)
return
}
status, err := job.Wait(ctx)
if err != nil {
log.Printf("error: %s", err)
w.WriteHeader(500)
return
}
if err := status.Err(); err != nil {
log.Printf("error: %s", err)
w.WriteHeader(500)
return
}
}
func gsPrefix(projectID string) string {
return fmt.Sprintf("gs://%s-backup-firestore", projectID)
}
func savePath(projectID string) string {
return fmt.Sprintf("projects/%s/databases/(default)", projectID)
}