-
Notifications
You must be signed in to change notification settings - Fork 111
/
sql_store.go
282 lines (238 loc) · 8 KB
/
sql_store.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
package athena
import (
"context"
"errors"
"fmt"
"net/url"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/athena"
types2 "github.com/aws/aws-sdk-go-v2/service/athena/types"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/google/uuid"
"github.com/mitchellh/mapstructure"
"github.com/rilldata/rill/runtime/drivers"
rillblob "github.com/rilldata/rill/runtime/drivers/blob"
"gocloud.dev/blob"
"gocloud.dev/blob/s3blob"
)
func (c *Connection) Query(_ context.Context, _ map[string]any) (drivers.RowIterator, error) {
return nil, drivers.ErrNotImplemented
}
func (c *Connection) QueryAsFiles(ctx context.Context, props map[string]any, _ *drivers.QueryOption, _ drivers.Progress) (outIt drivers.FileIterator, outErr error) {
conf, err := parseSourceProperties(props)
if err != nil {
return nil, fmt.Errorf("failed to parse config: %w", err)
}
awsConfig, err := c.awsConfig(ctx, conf.AWSRegion)
if err != nil {
return nil, err
}
client := athena.NewFromConfig(awsConfig)
outputLocation, err := resolveOutputLocation(ctx, client, conf)
if err != nil {
return nil, err
}
outputURL, err := url.Parse(outputLocation)
if err != nil {
return nil, err
}
// outputLocation s3://bucket/path
// unloadLocation s3://bucket/path/rill-tmp-<uuid>
// unloadPath path/rill-tmp-<uuid>
unloadFolderName := "rill-tmp-" + uuid.New().String()
bucketName := outputURL.Hostname()
unloadURL := outputURL.JoinPath(unloadFolderName)
unloadLocation := unloadURL.String()
unloadPath := strings.TrimPrefix(unloadURL.Path, "/")
cleanupFn := func() error {
return deleteObjectsInPrefix(ctx, awsConfig, bucketName, unloadPath)
}
err = c.unload(ctx, client, conf, unloadLocation)
if err != nil {
unloadErr := fmt.Errorf("failed to unload: %w", err)
cleanupErr := cleanupFn()
if cleanupErr != nil {
cleanupErr = fmt.Errorf("cleanup error: %w", cleanupErr)
}
return nil, errors.Join(unloadErr, cleanupErr)
}
defer func() {
if outErr != nil {
cleanupErr := cleanupFn()
if cleanupErr != nil {
outErr = errors.Join(outErr, fmt.Errorf("cleanup error: %w", cleanupErr))
}
}
}()
bucketObj, err := openBucket(ctx, awsConfig, bucketName)
if err != nil {
return nil, fmt.Errorf("cannot open bucket %q: %w", bucketName, err)
}
opts := rillblob.Options{
GlobPattern: unloadPath + "/**",
Format: "parquet",
}
it, err := rillblob.NewIterator(ctx, bucketObj, opts, c.logger)
if err != nil {
return nil, fmt.Errorf("cannot download parquet output %q %w", opts.GlobPattern, err)
}
return autoDeleteFileIterator{
FileIterator: it,
cleanupFn: cleanupFn,
}, nil
}
func (c *Connection) awsConfig(ctx context.Context, awsRegion string) (aws.Config, error) {
loadOptions := []func(*config.LoadOptions) error{
// Setting the default region to an empty string, will result in the default region value being ignored
config.WithDefaultRegion("us-east-1"),
// Setting the region to an empty string, will result in the region value being ignored
config.WithRegion(awsRegion),
}
// If one of the static properties is specified: access key, secret key, or session token, use static credentials,
// Else fallback to the SDK's default credential chain (environment, instance, etc) unless AllowHostAccess is false
if c.config.AccessKeyID != "" || c.config.SecretAccessKey != "" || c.config.SessionToken != "" {
p := credentials.NewStaticCredentialsProvider(c.config.AccessKeyID, c.config.SecretAccessKey, c.config.SessionToken)
loadOptions = append(loadOptions, config.WithCredentialsProvider(p))
} else if !c.config.AllowHostAccess {
return aws.Config{}, fmt.Errorf("static creds are not provided, and host access is not allowed")
}
return config.LoadDefaultConfig(ctx, loadOptions...)
}
func (c *Connection) unload(ctx context.Context, client *athena.Client, conf *sourceProperties, unloadLocation string) error {
finalSQL := fmt.Sprintf("UNLOAD (%s\n) TO '%s' WITH (format = 'PARQUET')", conf.SQL, unloadLocation)
executeParams := &athena.StartQueryExecutionInput{
QueryString: aws.String(finalSQL),
}
if conf.OutputLocation != "" {
executeParams.ResultConfiguration = &types2.ResultConfiguration{
OutputLocation: aws.String(conf.OutputLocation),
}
}
if conf.Workgroup != "" { // primary is used if nothing is set
executeParams.WorkGroup = aws.String(conf.Workgroup)
}
queryExecutionOutput, err := client.StartQueryExecution(ctx, executeParams)
if err != nil {
return err
}
for {
select {
case <-ctx.Done():
_, err = client.StopQueryExecution(ctx, &athena.StopQueryExecutionInput{
QueryExecutionId: queryExecutionOutput.QueryExecutionId,
})
return errors.Join(ctx.Err(), err)
default:
status, err := client.GetQueryExecution(ctx, &athena.GetQueryExecutionInput{
QueryExecutionId: queryExecutionOutput.QueryExecutionId,
})
if err != nil {
return err
}
switch status.QueryExecution.Status.State {
case types2.QueryExecutionStateSucceeded:
return nil
case types2.QueryExecutionStateCancelled:
return fmt.Errorf("Athena query execution cancelled")
case types2.QueryExecutionStateFailed:
return fmt.Errorf("Athena query execution failed %s", *status.QueryExecution.Status.AthenaError.ErrorMessage)
}
}
time.Sleep(time.Second)
}
}
func parseSourceProperties(props map[string]any) (*sourceProperties, error) {
conf := &sourceProperties{}
err := mapstructure.Decode(props, conf)
if err != nil {
return nil, err
}
return conf, nil
}
func resolveOutputLocation(ctx context.Context, client *athena.Client, conf *sourceProperties) (string, error) {
if conf.OutputLocation != "" {
return conf.OutputLocation, nil
}
workgroup := conf.Workgroup
// fallback to "primary" (default) workgroup if no workgroup is specified
if workgroup == "" {
workgroup = "primary"
}
wo, err := client.GetWorkGroup(ctx, &athena.GetWorkGroupInput{
WorkGroup: aws.String(workgroup),
})
if err != nil {
return "", err
}
resultConfiguration := wo.WorkGroup.Configuration.ResultConfiguration
if resultConfiguration != nil && resultConfiguration.OutputLocation != nil && *resultConfiguration.OutputLocation != "" {
return *resultConfiguration.OutputLocation, nil
}
return "", fmt.Errorf("either output_location or workgroup with an output location must be set")
}
func openBucket(ctx context.Context, cfg aws.Config, bucket string) (*blob.Bucket, error) {
s3client := s3.NewFromConfig(cfg)
return s3blob.OpenBucketV2(ctx, s3client, bucket, nil)
}
func deleteObjectsInPrefix(ctx context.Context, cfg aws.Config, bucketName, prefix string) error {
s3client := s3.NewFromConfig(cfg)
deleteBatch := func(objects []types.ObjectIdentifier) error {
_, err := s3client.DeleteObjects(ctx, &s3.DeleteObjectsInput{
Bucket: &bucketName,
Delete: &types.Delete{
Objects: objects,
},
})
return err
}
var continuationToken *string
for {
out, err := s3client.ListObjectsV2(ctx, &s3.ListObjectsV2Input{
Bucket: &bucketName,
Prefix: &prefix,
ContinuationToken: continuationToken,
})
if err != nil {
return err
}
ids := make([]types.ObjectIdentifier, 0, len(out.Contents))
for _, o := range out.Contents {
ids = append(ids, types.ObjectIdentifier{
Key: o.Key,
})
}
if len(ids) > 0 {
if err := deleteBatch(ids); err != nil {
return err
}
}
if out.IsTruncated && out.NextContinuationToken != nil {
continuationToken = out.NextContinuationToken
} else {
break
}
}
return nil
}
type sourceProperties struct {
SQL string `mapstructure:"sql"`
OutputLocation string `mapstructure:"output_location"`
Workgroup string `mapstructure:"workgroup"`
AWSRegion string `mapstructure:"region"`
}
type autoDeleteFileIterator struct {
drivers.FileIterator
cleanupFn func() error
}
func (i autoDeleteFileIterator) Close() error {
err := i.FileIterator.Close()
if err != nil {
return err
}
return i.cleanupFn()
}