-
Notifications
You must be signed in to change notification settings - Fork 500
/
write.go
237 lines (208 loc) · 7.44 KB
/
write.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
package client
import (
"context"
"fmt"
"os"
"slices"
"strings"
"time"
"github.com/apache/arrow/go/v16/arrow"
"github.com/apache/arrow/go/v16/parquet"
"github.com/apache/arrow/go/v16/parquet/pqarrow"
"github.com/cenkalti/backoff/v4"
"github.com/cloudquery/plugin-sdk/v4/message"
"github.com/cloudquery/plugin-sdk/v4/schema"
"github.com/google/uuid"
)
func nonPkIndices(sc *schema.Table) []int {
var indices []int
for i, c := range sc.Columns {
if !c.PrimaryKey {
indices = append(indices, i)
}
}
return indices
}
// At time of writing (March 2023), duckdb does not support updating list columns.
// As a workaround, we delete the row and insert it again. This makes it non-atomic, unfortunately,
// but this is unavoidable until support is added to duckdb itself.
// See https://github.com/duckdb/duckdb/blob/c5d9afb97bbf0be12216f3b89ae3131afbbc3156/src/storage/table/list_column_data.cpp#L243-L251
func containsList(sc *schema.Table) bool {
return slices.ContainsFunc(sc.Columns, func(c schema.Column) bool { return dtContainsList(c.Type) })
}
func dtContainsList(dt arrow.DataType) bool {
switch dt := dt.(type) {
case *arrow.StructType:
return slices.ContainsFunc(dt.Fields(), func(f arrow.Field) bool { return dtContainsList(f.Type) })
case *arrow.MapType:
return dtContainsList(dt.KeyType()) || dtContainsList(dt.ItemType())
case arrow.ListLikeType:
return true
default:
return false
}
}
func (c *Client) upsert(ctx context.Context, tmpTableName string, table *schema.Table) error {
var sb strings.Builder
sb.WriteString("INSERT INTO ")
sb.WriteString(table.Name)
sb.WriteString("(" + strings.Join(sanitized(table.Columns.Names()), ", ") + ")")
sb.WriteString(" SELECT ")
sb.WriteString(strings.Join(sanitized(table.Columns.Names()), ", "))
sb.WriteString(" FROM ")
sb.WriteString(tmpTableName)
sb.WriteString(" ON CONFLICT (" + strings.Join(table.PrimaryKeys(), ", ") + ")")
indices := nonPkIndices(table)
if len(indices) == 0 {
sb.WriteString(" DO NOTHING")
return c.exec(ctx, sb.String())
}
sb.WriteString(" DO UPDATE SET ")
written := 0
for _, index := range nonPkIndices(table) {
col := table.Columns[index]
if col.Unique {
// we skip this stuff, as unique constraint can't be updated by DuckDB
continue
}
if written > 0 {
sb.WriteString(", ")
}
sb.WriteString(sanitizeID(col.Name))
sb.WriteString(" = excluded.")
sb.WriteString(sanitizeID(col.Name))
written++
}
query := sb.String()
// return c.exec(ctx, query)
// per https://duckdb.org/docs/sql/indexes#over-eager-unique-constraint-checking we might need some retries
// as the upsert for tables with PKs is transformed into delete + insert internally
return backoff.Retry(
func() error {
return c.exec(ctx, query)
},
backoff.WithContext(backoff.WithMaxRetries(backoff.NewConstantBackOff(50*time.Millisecond), 3), ctx),
)
}
func (c *Client) deleteByPK(ctx context.Context, tmpTableName string, table *schema.Table) error {
var sb strings.Builder
sb.WriteString("delete from " + table.Name + " using " + tmpTableName + " where ")
for i, col := range table.PrimaryKeys() {
if i > 0 {
sb.WriteString(" and ")
}
sb.WriteString(table.Name + "." + sanitizeID(col))
sb.WriteString(" = ")
sb.WriteString(tmpTableName + "." + sanitizeID(col))
}
return c.exec(ctx, sb.String())
}
func (c *Client) copyFromFile(ctx context.Context, tableName string, fileName string, table *schema.Table) error {
return c.exec(ctx, "copy "+tableName+
"("+strings.Join(sanitized(table.Columns.Names()), ", ")+
") from '"+fileName+"' (FORMAT PARQUET)")
}
func (c *Client) Write(ctx context.Context, msgs <-chan message.WriteMessage) error {
if err := c.writer.Write(ctx, msgs); err != nil {
return fmt.Errorf("failed to write messages: %w", err)
}
if err := c.writer.Flush(ctx); err != nil {
return fmt.Errorf("failed to flush messages: %w", err)
}
return nil
}
func (c *Client) WriteTableBatch(ctx context.Context, name string, msgs message.WriteInserts) error {
if len(msgs) == 0 {
return nil
}
table := msgs[0].GetTable()
writeStart := time.Now()
tmpFile, err := writeTMPFile(table, msgs)
if err != nil {
return err
}
c.logger.Debug().Str("table", table.Name).Str("duration", time.Since(writeStart).String()).Msg("write tmp file")
defer os.Remove(tmpFile)
if len(table.PrimaryKeys()) == 0 {
copyStart := time.Now()
defer func() {
c.logger.Debug().Str("table", table.Name).Str("duration", time.Since(copyStart).String()).Msg("copy file to table")
}()
return c.copyFromFile(ctx, name, tmpFile, table)
}
tmpTableName := name + strings.ReplaceAll(uuid.New().String(), "-", "_")
if err := c.createTableIfNotExist(ctx, tmpTableName, table); err != nil {
return fmt.Errorf("failed to create table %s: %w", tmpTableName, err)
}
defer func() {
e := c.exec(ctx, "drop table "+tmpTableName)
if err == nil {
// we preserve original error, so update only on nil err
err = e
}
}()
if err := c.copyFromFile(ctx, tmpTableName, tmpFile, table); err != nil {
return fmt.Errorf("failed to copy from file %s: %w", tmpFile, err)
}
// At time of writing (March 2023), duckdb does not support updating list columns.
// As a workaround, we delete the row and insert it again. This makes it non-atomic, unfortunately,
// but this is unavoidable until support is added to duckdb itself.
// See https://github.com/duckdb/duckdb/blob/c5d9afb97bbf0be12216f3b89ae3131afbbc3156/src/storage/table/list_column_data.cpp#L243-L251
if containsList(table) {
return c.deleteInsert(ctx, tmpTableName, table)
}
return c.upsert(ctx, tmpTableName, table)
}
func writeTMPFile(table *schema.Table, msgs []*message.WriteInsert) (fileName string, err error) {
sc := transformSchemaForWriting(table.ToArrowSchema())
// create temp file
f, err := os.CreateTemp("", fmt.Sprintf("%s-*.parquet", table.Name))
if err != nil {
return "", err
}
defer f.Close() // we don't care here, as the happy-path will actually check the error
fileName = f.Name()
// prep file writer
fw, err := pqarrow.NewFileWriter(sc, f,
parquet.NewWriterProperties(
parquet.WithVersion(parquet.V2_LATEST), // use latest
parquet.WithMaxRowGroupLength(128*1024*1024), // 128M
// parquet.WithCompression(compress.Codecs.Snappy),
),
pqarrow.NewArrowWriterProperties(pqarrow.WithStoreSchema()),
)
if err != nil {
return "", err
}
defer fw.Close() // we don't care here either as the happy path will check the error
// write records
for _, msg := range msgs {
if err = fw.WriteBuffered(transformRecord(sc, msg.Record)); err != nil {
return "", err
}
}
// close file writer (will close the underlying file, too)
return fileName, fw.Close()
}
func (c *Client) deleteInsert(ctx context.Context, tmpTableName string, table *schema.Table) error {
if err := c.deleteByPK(ctx, tmpTableName, table); err != nil {
return err
}
sb := new(strings.Builder)
sb.WriteString("INSERT INTO ")
sb.WriteString(table.Name)
sb.WriteString("(" + strings.Join(sanitized(table.Columns.Names()), ", ") + ")")
sb.WriteString(" SELECT ")
sb.WriteString(strings.Join(sanitized(table.Columns.Names()), ", "))
sb.WriteString(" FROM ")
sb.WriteString(tmpTableName)
sb.WriteString(" ON CONFLICT DO NOTHING")
query := sb.String()
// per https://duckdb.org/docs/sql/indexes#over-eager-unique-constraint-checking we might need to retry
return backoff.Retry(
func() error {
return c.exec(ctx, query)
},
backoff.WithContext(backoff.WithMaxRetries(backoff.NewConstantBackOff(50*time.Millisecond), 3), ctx),
)
}