-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathload.go
More file actions
288 lines (245 loc) · 11.1 KB
/
load.go
File metadata and controls
288 lines (245 loc) · 11.1 KB
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
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package bigquery
import (
"context"
"io"
"time"
"cloud.google.com/go/internal/trace"
bq "google.golang.org/api/bigquery/v2"
"google.golang.org/api/googleapi"
)
// LoadConfig holds the configuration for a load job.
type LoadConfig struct {
// Src is the source from which data will be loaded.
Src LoadSource
// Dst is the table into which the data will be loaded.
Dst *Table
// CreateDisposition specifies the circumstances under which the destination table will be created.
// The default is CreateIfNeeded.
CreateDisposition TableCreateDisposition
// WriteDisposition specifies how existing data in the destination table is treated.
// The default is WriteAppend.
WriteDisposition TableWriteDisposition
// The labels associated with this job.
Labels map[string]string
// If non-nil, the destination table is partitioned by time.
TimePartitioning *TimePartitioning
// If non-nil, the destination table is partitioned by integer range.
RangePartitioning *RangePartitioning
// Clustering specifies the data clustering configuration for the destination table.
Clustering *Clustering
// Custom encryption configuration (e.g., Cloud KMS keys).
DestinationEncryptionConfig *EncryptionConfig
// Allows the schema of the destination table to be updated as a side effect of
// the load job.
SchemaUpdateOptions []string
// For Avro-based loads, controls whether logical type annotations are used.
// See https://cloud.google.com/bigquery/docs/loading-data-cloud-storage-avro#logical_types
// for additional information.
UseAvroLogicalTypes bool
// For ingestion from datastore backups, ProjectionFields governs which fields
// are projected from the backup. The default behavior projects all fields.
ProjectionFields []string
// HivePartitioningOptions allows use of Hive partitioning based on the
// layout of objects in Cloud Storage.
HivePartitioningOptions *HivePartitioningOptions
// DecimalTargetTypes allows selection of how decimal values are converted when
// processed in bigquery, subject to the value type having sufficient precision/scale
// to support the values. In the order of NUMERIC, BIGNUMERIC, and STRING, a type is
// selected if is present in the list and if supports the necessary precision and scale.
//
// StringTargetType supports all precision and scale values.
DecimalTargetTypes []DecimalTargetType
// Sets a best-effort deadline on a specific job. If job execution exceeds this
// timeout, BigQuery may attempt to cancel this work automatically.
//
// This deadline cannot be adjusted or removed once the job is created. Consider
// using Job.Cancel in situations where you need more dynamic behavior.
//
// Experimental: this option is experimental and may be modified or removed in future versions,
// regardless of any other documented package stability guarantees.
JobTimeout time.Duration
// When loading a table with external data, the user can provide a reference file with the table schema.
// This is enabled for the following formats: AVRO, PARQUET, ORC.
ReferenceFileSchemaURI string
// If true, creates a new session, where session id will
// be a server generated random id. If false, runs query with an
// existing session_id passed in ConnectionProperty, otherwise runs the
// load job in non-session mode.
CreateSession bool
// ConnectionProperties are optional key-values settings.
ConnectionProperties []*ConnectionProperty
// MediaOptions stores options for customizing media upload.
MediaOptions []googleapi.MediaOption
// Controls the behavior of column naming during a load job.
// For more information, see:
// https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#columnnamecharactermap
ColumnNameCharacterMap ColumnNameCharacterMap
// The reservation that job would use. User can specify a reservation to
// execute the job. If reservation is not set, reservation is determined
// based on the rules defined by the reservation assignments. The expected
// format is
// `projects/{project}/locations/{location}/reservations/{reservation}`.
Reservation string
// A target limit on the rate of slot consumption by this query. If set to a
// value > 0, BigQuery will attempt to limit the rate of slot consumption by
// this query to keep it below the configured limit, even if the query is
// eligible for more slots based on fair scheduling. The unused slots will be
// available for other jobs and queries to use.
//
// Note: This feature is not yet generally available.
MaxSlots int32
}
func (l *LoadConfig) toBQ() (*bq.JobConfiguration, io.Reader) {
config := &bq.JobConfiguration{
Labels: l.Labels,
Load: &bq.JobConfigurationLoad{
CreateDisposition: string(l.CreateDisposition),
WriteDisposition: string(l.WriteDisposition),
DestinationTable: l.Dst.toBQ(),
TimePartitioning: l.TimePartitioning.toBQ(),
RangePartitioning: l.RangePartitioning.toBQ(),
Clustering: l.Clustering.toBQ(),
DestinationEncryptionConfiguration: l.DestinationEncryptionConfig.toBQ(),
SchemaUpdateOptions: l.SchemaUpdateOptions,
UseAvroLogicalTypes: l.UseAvroLogicalTypes,
ProjectionFields: l.ProjectionFields,
HivePartitioningOptions: l.HivePartitioningOptions.toBQ(),
ReferenceFileSchemaUri: l.ReferenceFileSchemaURI,
CreateSession: l.CreateSession,
ColumnNameCharacterMap: string(l.ColumnNameCharacterMap),
},
JobTimeoutMs: l.JobTimeout.Milliseconds(),
}
for _, v := range l.DecimalTargetTypes {
config.Load.DecimalTargetTypes = append(config.Load.DecimalTargetTypes, string(v))
}
for _, v := range l.ConnectionProperties {
config.Load.ConnectionProperties = append(config.Load.ConnectionProperties, v.toBQ())
}
media := l.Src.populateLoadConfig(config.Load)
config.Reservation = l.Reservation
config.MaxSlots = int64(l.MaxSlots)
return config, media
}
func bqToLoadConfig(q *bq.JobConfiguration, c *Client) *LoadConfig {
lc := &LoadConfig{
Labels: q.Labels,
CreateDisposition: TableCreateDisposition(q.Load.CreateDisposition),
WriteDisposition: TableWriteDisposition(q.Load.WriteDisposition),
Dst: bqToTable(q.Load.DestinationTable, c),
TimePartitioning: bqToTimePartitioning(q.Load.TimePartitioning),
RangePartitioning: bqToRangePartitioning(q.Load.RangePartitioning),
Clustering: bqToClustering(q.Load.Clustering),
DestinationEncryptionConfig: bqToEncryptionConfig(q.Load.DestinationEncryptionConfiguration),
SchemaUpdateOptions: q.Load.SchemaUpdateOptions,
UseAvroLogicalTypes: q.Load.UseAvroLogicalTypes,
ProjectionFields: q.Load.ProjectionFields,
HivePartitioningOptions: bqToHivePartitioningOptions(q.Load.HivePartitioningOptions),
ReferenceFileSchemaURI: q.Load.ReferenceFileSchemaUri,
CreateSession: q.Load.CreateSession,
ColumnNameCharacterMap: ColumnNameCharacterMap(q.Load.ColumnNameCharacterMap),
Reservation: q.Reservation,
MaxSlots: int32(q.MaxSlots),
}
if q.JobTimeoutMs > 0 {
lc.JobTimeout = time.Duration(q.JobTimeoutMs) * time.Millisecond
}
for _, v := range q.Load.DecimalTargetTypes {
lc.DecimalTargetTypes = append(lc.DecimalTargetTypes, DecimalTargetType(v))
}
for _, v := range q.Load.ConnectionProperties {
lc.ConnectionProperties = append(lc.ConnectionProperties, bqToConnectionProperty(v))
}
var fc *FileConfig
if len(q.Load.SourceUris) == 0 {
s := NewReaderSource(nil)
fc = &s.FileConfig
lc.Src = s
} else {
s := NewGCSReference(q.Load.SourceUris...)
fc = &s.FileConfig
lc.Src = s
}
bqPopulateFileConfig(q.Load, fc)
return lc
}
// A Loader loads data from Google Cloud Storage into a BigQuery table.
type Loader struct {
JobIDConfig
LoadConfig
c *Client
}
// A LoadSource represents a source of data that can be loaded into
// a BigQuery table.
//
// This package defines two LoadSources: GCSReference, for Google Cloud Storage
// objects, and ReaderSource, for data read from an io.Reader.
type LoadSource interface {
// populates config, returns media
populateLoadConfig(*bq.JobConfigurationLoad) io.Reader
}
// LoaderFrom returns a Loader which can be used to load data into a BigQuery table.
// The returned Loader may optionally be further configured before its Run method is called.
// See GCSReference and ReaderSource for additional configuration options that
// affect loading.
func (t *Table) LoaderFrom(src LoadSource) *Loader {
return &Loader{
c: t.c,
LoadConfig: LoadConfig{
Src: src,
Dst: t,
},
}
}
// Run initiates a load job.
func (l *Loader) Run(ctx context.Context) (j *Job, err error) {
ctx = trace.StartSpan(ctx, "cloud.google.com/go/bigquery.Load.Run")
defer func() { trace.EndSpan(ctx, err) }()
job, media := l.newJob()
return l.c.insertJob(ctx, job, media, l.LoadConfig.MediaOptions...)
}
func (l *Loader) newJob() (*bq.Job, io.Reader) {
config, media := l.LoadConfig.toBQ()
return &bq.Job{
JobReference: l.JobIDConfig.createJobRef(l.c),
Configuration: config,
}, media
}
// DecimalTargetType is used to express preference ordering for converting values from external formats.
type DecimalTargetType string
var (
// NumericTargetType indicates the preferred type is NUMERIC when supported.
NumericTargetType DecimalTargetType = "NUMERIC"
// BigNumericTargetType indicates the preferred type is BIGNUMERIC when supported.
BigNumericTargetType DecimalTargetType = "BIGNUMERIC"
// StringTargetType indicates the preferred type is STRING when supported.
StringTargetType DecimalTargetType = "STRING"
)
// ColumnNameCharacterMap is used to specific column naming behavior for load jobs.
type ColumnNameCharacterMap string
var (
// UnspecifiedColumnNameCharacterMap is the unspecified default value.
UnspecifiedColumnNameCharacterMap ColumnNameCharacterMap = "COLUMN_NAME_CHARACTER_MAP_UNSPECIFIED"
// StrictColumnNameCharacterMap indicates support for flexible column names.
// Invalid column names will be rejected.
StrictColumnNameCharacterMap ColumnNameCharacterMap = "STRICT"
// V1ColumnNameCharacterMap indicates support for alphanumeric + underscore characters and names must start with a letter or underscore.
// Invalid column names will be normalized.
V1ColumnNameCharacterMap ColumnNameCharacterMap = "V1"
// V2ColumnNameCharacterMap indicates support for flexible column names.
// Invalid column names will be normalized.
V2ColumnNameCharacterMap ColumnNameCharacterMap = "V2"
)