generated from keboola/template
/
table.go
414 lines (346 loc) · 12.4 KB
/
table.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
package storageapi
import (
"bytes"
"context"
"encoding/csv"
jsonLib "encoding/json"
"fmt"
"mime/multipart"
"net/textproto"
"sort"
"strings"
"time"
"github.com/relvacode/iso8601"
"github.com/keboola/go-client/pkg/client"
)
// Table https://keboola.docs.apiary.io/#reference/tables/list-tables/list-all-tables
type Table struct {
ID TableID `json:"id"`
Uri string `json:"uri"`
Name string `json:"name"`
DisplayName string `json:"displayName"`
PrimaryKey []string `json:"primaryKey"`
Created iso8601.Time `json:"created"`
LastImportDate iso8601.Time `json:"lastImportDate"`
LastChangeDate *iso8601.Time `json:"lastChangeDate"`
RowsCount uint64 `json:"rowsCount"`
DataSizeBytes uint64 `json:"dataSizeBytes"`
Columns []string `json:"columns"`
Metadata []MetadataDetail `json:"metadata"`
ColumnMetadata ColumnMetadata `json:"columnMetadata"`
Bucket *Bucket `json:"bucket"`
}
type ColumnMetadata map[string]MetadataDetail
// UnmarshalJSON implements JSON decoding.
// The API returns empty value as empty array.
func (r *ColumnMetadata) UnmarshalJSON(data []byte) (err error) {
if string(data) == "[]" {
*r = ColumnMetadata{}
return nil
}
// see https://stackoverflow.com/questions/43176625/call-json-unmarshal-inside-unmarshaljson-function-without-causing-stack-overflow
type _r ColumnMetadata
return jsonLib.Unmarshal(data, (*_r)(r))
}
type listTablesConfig struct {
include map[string]bool
}
func (v listTablesConfig) includeString() string {
include := make([]string, 0, len(v.include))
for k := range v.include {
include = append(include, k)
}
sort.Strings(include)
return strings.Join(include, ",")
}
type Option func(c *listTablesConfig)
func WithBuckets() Option {
return func(c *listTablesConfig) {
c.include["buckets"] = true
}
}
func WithColumns() Option {
return func(c *listTablesConfig) {
c.include["columns"] = true
}
}
func WithMetadata() Option {
return func(c *listTablesConfig) {
c.include["metadata"] = true
}
}
func WithColumnMetadata() Option {
return func(c *listTablesConfig) {
c.include["columnMetadata"] = true
}
}
// ListTablesRequest https://keboola.docs.apiary.io/#reference/tables/list-tables/list-all-tables
func ListTablesRequest(opts ...Option) client.APIRequest[*[]*Table] {
config := listTablesConfig{include: make(map[string]bool)}
for _, opt := range opts {
opt(&config)
}
result := make([]*Table, 0)
request := newRequest().
WithResult(&result).
WithGet("tables").
AndQueryParam("include", config.includeString())
return client.NewAPIRequest(&result, request)
}
func writeHeaderToCSV(ctx context.Context, file *File, columns []string) (err error) {
// Upload file with the header
bw, err := NewUploadWriter(ctx, file)
if err != nil {
return fmt.Errorf("connecting to the bucket failed: %w", err)
}
defer func() {
if closeErr := bw.Close(); closeErr != nil && err == nil {
err = fmt.Errorf("cannot close bucket writer: %w", closeErr)
}
}()
header, err := columnsToCSVHeader(columns)
if err != nil {
return err
}
_, err = bw.Write(header)
return err
}
func columnsToCSVHeader(columns []string) ([]byte, error) {
var str bytes.Buffer
cw := csv.NewWriter(&str)
if err := cw.Write(columns); err != nil {
return nil, fmt.Errorf("error writing header to csv: %w", err)
}
cw.Flush()
if err := cw.Error(); err != nil {
return nil, fmt.Errorf("error writing header to csv: %w", err)
}
return str.Bytes(), nil
}
// CreateTable creates an empty table with given columns.
func CreateTable(ctx context.Context, sender client.Sender, tableID TableID, columns []string, opts ...CreateTableOption) (*Table, error) {
// Create file resource
file, err := CreateFileResourceRequest(&File{Name: tableID.TableName}).Send(ctx, sender)
if err != nil {
return nil, fmt.Errorf("creating file failed: %w", err)
}
// Upload file with the header
if err := writeHeaderToCSV(ctx, file, columns); err != nil {
return nil, fmt.Errorf("error writing header to csv: %w", err)
}
// Create the table from the header file
return CreateTableFromFileRequest(tableID, file.ID, opts...).Send(ctx, sender)
}
// loadDataFromFileConfig contains common params to load data from file resource.
type loadDataFromFileConfig struct {
Delimiter string `json:"delimiter,omitempty" writeoptional:"true"`
Enclosure string `json:"enclosure,omitempty" writeoptional:"true"`
EscapedBy string `json:"escapedBy,omitempty" writeoptional:"true"`
}
// delimiterOption specifies field delimiter used in the CSV file. Default value is ','.
type delimiterOption string
func WithDelimiter(d string) delimiterOption {
return delimiterOption(d)
}
// enclosureOption specifies field enclosure used in the CSV file. Default value is '"'.
type enclosureOption string
func WithEnclosure(e string) enclosureOption {
return enclosureOption(e)
}
// escapedByOption specifies escape character used in the CSV file. The default value is an empty value - no escape character is used.
// Note: you can specify either enclosure or escapedBy parameter, not both.
type escapedByOption string
func WithEscapedBy(e string) escapedByOption {
return escapedByOption(e)
}
// CreateTableOption applies to the request for creating table from file.
type CreateTableOption interface {
applyCreateTableOption(c *createTableConfig)
}
// createTableConfig contains params to create table from file resource.
type createTableConfig struct {
PrimaryKey string `json:"primaryKey,omitempty" writeoptional:"true"`
}
// primaryKeyOption specifies primary key of the table. Multiple columns can be separated by a comma.
type primaryKeyOption string
func (o primaryKeyOption) applyCreateTableOption(c *createTableConfig) {
c.PrimaryKey = string(o)
}
func WithPrimaryKey(pk []string) primaryKeyOption {
return primaryKeyOption(strings.Join(pk, ","))
}
// CreateTableDeprecatedSyncRequest https://keboola.docs.apiary.io/#reference/tables/create-or-list-tables/create-new-table-from-csv-file
func CreateTableDeprecatedSyncRequest(tableID TableID, columns []string, opts ...CreateTableOption) (client.APIRequest[*Table], error) {
c := &createTableConfig{}
for _, o := range opts {
o.applyCreateTableOption(c)
}
body := bytes.NewBufferString("")
mp := multipart.NewWriter(body)
// Write params
params := client.ToFormBody(client.StructToMap(c, nil))
params["name"] = tableID.TableName
for k, v := range params {
_ = mp.WriteField(k, v)
}
// Write CSV header
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition", `form-data; name="data"; filename="data.csv"`)
h.Set("Content-Type", "text/csv")
if wr, err := mp.CreatePart(h); err != nil {
return nil, fmt.Errorf(`could not add binary to multipart: %w`, err)
} else if csvHeader, err := columnsToCSVHeader(columns); err != nil {
return nil, fmt.Errorf(`could not convert columns to CSV header: %w`, err)
} else if _, err := wr.Write(csvHeader); err != nil {
return nil, fmt.Errorf(`could not write CSV header to multipart: %w`, err)
}
// Close body
if err := mp.Close(); err != nil {
return nil, fmt.Errorf(`could not close multipart: %w`, err)
}
table := &Table{}
request := newRequest().
WithResult(table).
WithPost("buckets/{bucketId}/tables").
AndPathParam("bucketId", tableID.BucketID.String()).
WithBody(bytes.NewReader(body.Bytes())).
WithContentType(fmt.Sprintf("multipart/form-data;boundary=%v", mp.Boundary())).
WithOnError(ignoreResourceAlreadyExistsError(func(ctx context.Context, sender client.Sender) error {
if result, err := GetTableRequest(table.ID).Send(ctx, sender); err == nil {
*table = *result
return nil
} else {
return err
}
}))
return client.NewAPIRequest(table, request), nil
}
// CreateTableFromFileRequest https://keboola.docs.apiary.io/#reference/tables/create-table-asynchronously/create-new-table-from-csv-file-asynchronously
func CreateTableFromFileRequest(tableID TableID, dataFileID int, opts ...CreateTableOption) client.APIRequest[*Table] {
c := &createTableConfig{}
for _, o := range opts {
o.applyCreateTableOption(c)
}
params := client.StructToMap(c, nil)
params["name"] = tableID.TableName
params["dataFileId"] = dataFileID
job := &Job{}
table := &Table{}
request := newRequest().
WithResult(job).
WithPost("buckets/{bucketId}/tables-async").
AndPathParam("bucketId", tableID.BucketID.String()).
WithFormBody(client.ToFormBody(params)).
WithOnSuccess(func(ctx context.Context, sender client.Sender, _ client.HTTPResponse) error {
// Wait for storage job
waitCtx, waitCancelFn := context.WithTimeout(ctx, time.Minute*1)
defer waitCancelFn()
return WaitForJob(waitCtx, sender, job)
}).
WithOnSuccess(func(_ context.Context, _ client.Sender, _ client.HTTPResponse) error {
bytes, err := jsonLib.Marshal(job.Results)
if err != nil {
return fmt.Errorf(`cannot encode create table results: %w`, err)
}
err = jsonLib.Unmarshal(bytes, &table)
if err != nil {
return fmt.Errorf(`cannot decode create table results: %w`, err)
}
return nil
})
return client.NewAPIRequest(table, request)
}
// LoadDataOption applies to the request loading data to a table.
type LoadDataOption interface {
applyLoadDataOption(c *loadDataConfig)
}
// loadDataConfig contains params to load data to a table from file resource.
type loadDataConfig struct {
loadDataFromFileConfig
IncrementalLoad int `json:"incremental,omitempty" writeoptional:"true"`
WithoutHeaders int `json:"withoutHeaders,omitempty" writeoptional:"true"`
Columns []string `json:"columns,omitempty" writeoptional:"true"`
}
func (o delimiterOption) applyLoadDataOption(c *loadDataConfig) {
c.Delimiter = string(o)
}
func (o enclosureOption) applyLoadDataOption(c *loadDataConfig) {
c.Enclosure = string(o)
}
func (o escapedByOption) applyLoadDataOption(c *loadDataConfig) {
c.EscapedBy = string(o)
}
// incrementalLoadOption decides whether the target table will be truncated before import.
type incrementalLoadOption bool
func (o incrementalLoadOption) applyLoadDataOption(c *loadDataConfig) {
c.IncrementalLoad = 0
if o {
c.IncrementalLoad = 1
}
}
func WithIncrementalLoad(i bool) incrementalLoadOption {
return incrementalLoadOption(i)
}
// columnsHeadersOption specifies list of columns present in the CSV file.
// The first line of the file will not be treated as a header.
type columnsHeadersOption []string
func (o columnsHeadersOption) applyLoadDataOption(c *loadDataConfig) {
c.Columns = o
}
func WithColumnsHeaders(c []string) columnsHeadersOption {
return c
}
// withoutHeaderOption specifies if the csv file contains header. If it doesn't, columns are matched by their order.
// If this option is used, columns option is ignored.
type withoutHeaderOption bool
func (o withoutHeaderOption) applyLoadDataOption(c *loadDataConfig) {
c.WithoutHeaders = 0
if o {
c.WithoutHeaders = 1
}
}
func WithoutHeader(h bool) withoutHeaderOption {
return withoutHeaderOption(h)
}
// LoadDataFromFileRequest https://keboola.docs.apiary.io/#reference/tables/load-data-asynchronously/import-data
func LoadDataFromFileRequest(tableID TableID, dataFileID int, opts ...LoadDataOption) client.APIRequest[*Job] {
c := &loadDataConfig{}
for _, o := range opts {
o.applyLoadDataOption(c)
}
params := client.StructToMap(c, nil)
params["dataFileId"] = dataFileID
job := &Job{}
request := newRequest().
WithResult(job).
WithPost("tables/{tableId}/import-async").
AndPathParam("tableId", tableID.String()).
WithFormBody(client.ToFormBody(params))
return client.NewAPIRequest(job, request)
}
// GetTableRequest https://keboola.docs.apiary.io/#reference/tables/manage-tables/table-detail
func GetTableRequest(tableID TableID) client.APIRequest[*Table] {
table := &Table{}
request := newRequest().
WithResult(table).
WithGet("tables/{tableId}").
AndPathParam("tableId", tableID.String())
return client.NewAPIRequest(table, request)
}
// DeleteTableRequest https://keboola.docs.apiary.io/#reference/tables/manage-tables/drop-table
func DeleteTableRequest(tableID TableID, opts ...DeleteOption) client.APIRequest[client.NoResult] {
c := &deleteConfig{
force: false,
}
for _, opt := range opts {
opt(c)
}
request := newRequest().
WithDelete("tables/{tableId}").
WithOnError(ignoreResourceNotFoundError()).
AndPathParam("tableId", tableID.String())
if c.force {
request = request.AndQueryParam("force", "true")
}
return client.NewAPIRequest(client.NoResult{}, request)
}