-
Notifications
You must be signed in to change notification settings - Fork 198
Expand file tree
/
Copy pathclickhouse.go
More file actions
446 lines (410 loc) · 12.9 KB
/
Copy pathclickhouse.go
File metadata and controls
446 lines (410 loc) · 12.9 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
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
package e2e
import (
"context"
"fmt"
"math/big"
"reflect"
"strings"
"testing"
"time"
"github.com/ClickHouse/clickhouse-go/v2"
"github.com/ClickHouse/clickhouse-go/v2/lib/chcol"
"github.com/ClickHouse/clickhouse-go/v2/lib/driver"
"github.com/google/uuid"
"github.com/shopspring/decimal"
"github.com/stretchr/testify/require"
"github.com/PeerDB-io/peerdb/flow/connectors"
connclickhouse "github.com/PeerDB-io/peerdb/flow/connectors/clickhouse"
"github.com/PeerDB-io/peerdb/flow/generated/protos"
"github.com/PeerDB-io/peerdb/flow/internal"
"github.com/PeerDB-io/peerdb/flow/model"
"github.com/PeerDB-io/peerdb/flow/shared"
"github.com/PeerDB-io/peerdb/flow/shared/types"
)
type ClickHouseSuite struct {
t *testing.T
source SuiteSource
s3Helper *S3TestHelper
connector *connclickhouse.ClickHouseConnector
catalog shared.CatalogPool
suffix string
cluster bool
}
func (s ClickHouseSuite) T() *testing.T {
return s.t
}
func (s ClickHouseSuite) Connector() connectors.Connector {
return s.source.Connector()
}
func (s ClickHouseSuite) Source() SuiteSource {
return s.source
}
func (s ClickHouseSuite) DestinationConnector() connectors.Connector {
return s.connector
}
func (s ClickHouseSuite) Suffix() string {
return s.suffix
}
func (s ClickHouseSuite) Peer() *protos.Peer {
dbname := "e2e_test_" + s.suffix
if s.cluster {
ret := &protos.Peer{
Name: AddSuffix(s, dbname),
Type: protos.DBType_CLICKHOUSE,
Config: &protos.Peer_ClickhouseConfig{
ClickhouseConfig: &protos.ClickhouseConfig{
Host: internal.ClickHouseTestHost(),
Port: 9001,
Database: dbname,
DisableTls: true,
S3: s.s3Helper.S3Config,
Cluster: "cicluster",
Replicated: false,
},
},
}
CreatePeer(s.t, ret)
return ret
} else {
return s.PeerForDatabase(dbname)
}
}
func (s ClickHouseSuite) PeerForDatabase(dbname string) *protos.Peer {
ret := &protos.Peer{
Name: AddSuffix(s, dbname),
Type: protos.DBType_CLICKHOUSE,
Config: &protos.Peer_ClickhouseConfig{
ClickhouseConfig: &protos.ClickhouseConfig{
Host: internal.ClickHouseTestHost(),
Port: internal.ClickHouseTestPort(),
Database: dbname,
DisableTls: true,
S3: s.s3Helper.S3Config,
},
},
}
CreatePeer(s.t, ret)
return ret
}
func (s ClickHouseSuite) DestinationTable(table string) string {
return table
}
func (s ClickHouseSuite) Teardown(ctx context.Context) {
require.NoError(s.t, s.s3Helper.CleanUp(ctx))
s.source.Teardown(s.t, ctx, s.Suffix())
require.NoError(s.t, s.connector.Close())
}
type TestClickHouseColumn struct {
Name string
Type string
}
// CreateRMTTable creates a ReplacingMergeTree table with the given name and columns.
func (s ClickHouseSuite) CreateRMTTable(tableName string, columns []TestClickHouseColumn, orderingKey string) error {
ch, err := connclickhouse.Connect(s.t.Context(), nil, s.Peer().GetClickhouseConfig())
if err != nil {
return err
}
defer ch.Close()
columnStrings := make([]string, len(columns))
for i, col := range columns {
columnStrings[i] = fmt.Sprintf("`%s` %s", col.Name, col.Type)
}
// Join the column definitions into a single string
columnStr := strings.Join(columnStrings, ", ")
// Create the table with ReplacingMergeTree engine
onCluster := ""
if s.cluster {
onCluster = " ON CLUSTER cicluster"
}
createTableQuery := fmt.Sprintf("CREATE TABLE `%s`%s (%s) ENGINE = ReplacingMergeTree() ORDER BY `%s`",
tableName, onCluster, columnStr, orderingKey)
return ch.Exec(s.t.Context(), createTableQuery)
}
func (s ClickHouseSuite) DropTable(tableName string) error {
ch, err := connclickhouse.Connect(s.t.Context(), nil, s.Peer().GetClickhouseConfig())
if err != nil {
return err
}
defer ch.Close()
dropTableQuery := fmt.Sprintf("DROP TABLE IF EXISTS `%s`", tableName)
return ch.Exec(s.t.Context(), dropTableQuery)
}
func (s ClickHouseSuite) GetRows(table string, cols string) (*model.QRecordBatch, error) {
peer := s.Peer()
ch, err := connclickhouse.Connect(s.t.Context(), nil, peer.GetClickhouseConfig())
if err != nil {
return nil, err
}
defer ch.Close()
var rows driver.Rows
var rowsErr error
if strings.HasPrefix(table, "_peerdb_raw") {
rows, rowsErr = s.queryRawTable(ch, table, cols)
} else {
rows, rowsErr = ch.Query(
s.t.Context(),
fmt.Sprintf(`SELECT %s FROM "%s" FINAL WHERE _peerdb_is_deleted = 0 ORDER BY 1 SETTINGS use_query_cache = false`, cols, table),
)
}
if rowsErr != nil {
return nil, rowsErr
}
defer rows.Close()
batch := &model.QRecordBatch{}
colTypes := rows.ColumnTypes()
scanTypes := make([]reflect.Type, len(colTypes))
tableSchema, err := connclickhouse.GetTableSchemaForTable(&protos.TableMapping{SourceTableIdentifier: table}, colTypes)
if err != nil {
return nil, err
}
for idx, ty := range colTypes {
fieldDesc := tableSchema.Columns[idx]
scanTypes[idx] = ty.ScanType()
batch.Schema.Fields = append(batch.Schema.Fields, types.QField{
Name: ty.Name(),
Type: types.QValueKind(fieldDesc.Type),
Precision: 0,
Scale: 0,
Nullable: fieldDesc.Nullable,
})
}
for rows.Next() {
// Allocate fresh scan targets per row: clickhouse-go does not reset a
// nullable destination to nil when scanning a NULL, so a reused buffer
// would make a NULL row inherit the previous row's value.
row := make([]any, len(scanTypes))
for idx, st := range scanTypes {
row[idx] = reflect.New(st).Interface()
}
if err := rows.Scan(row...); err != nil {
return nil, err
}
qrow := make([]types.QValue, 0, len(row))
for idx, val := range row {
switch v := val.(type) {
case **string:
if *v == nil {
qrow = append(qrow, types.QValueNull(types.QValueKindString))
} else {
qrow = append(qrow, types.QValueString{Val: **v})
}
case *string:
qrow = append(qrow, types.QValueString{Val: *v})
case *[]string:
qrow = append(qrow, types.QValueArrayString{Val: *v})
case **int8:
if *v == nil {
qrow = append(qrow, types.QValueNull(types.QValueKindInt8))
} else {
qrow = append(qrow, types.QValueInt8{Val: **v})
}
case *int8:
qrow = append(qrow, types.QValueInt8{Val: *v})
case **int16:
if *v == nil {
qrow = append(qrow, types.QValueNull(types.QValueKindInt16))
} else {
qrow = append(qrow, types.QValueInt16{Val: **v})
}
case *int16:
qrow = append(qrow, types.QValueInt16{Val: *v})
case **int32:
if *v == nil {
qrow = append(qrow, types.QValueNull(types.QValueKindInt32))
} else {
qrow = append(qrow, types.QValueInt32{Val: **v})
}
case *int32:
qrow = append(qrow, types.QValueInt32{Val: *v})
case *[]int32:
qrow = append(qrow, types.QValueArrayInt32{Val: *v})
case *[]int64:
qrow = append(qrow, types.QValueArrayInt64{Val: *v})
case *[]bool:
qrow = append(qrow, types.QValueArrayBoolean{Val: *v})
case **int64:
if *v == nil {
qrow = append(qrow, types.QValueNull(types.QValueKindInt64))
} else {
qrow = append(qrow, types.QValueInt64{Val: **v})
}
case *int64:
qrow = append(qrow, types.QValueInt64{Val: *v})
case **time.Time:
if *v == nil {
qrow = append(qrow, types.QValueNull(types.QValueKindTimestamp))
} else {
qrow = append(qrow, types.QValueTimestamp{Val: **v})
}
case **time.Duration:
if *v == nil {
qrow = append(qrow, types.QValueNull(types.QValueKindTime))
} else {
qrow = append(qrow, types.QValueTime{Val: **v})
}
case **uint8:
if *v == nil {
qrow = append(qrow, types.QValueNull(types.QValueKindUInt8))
} else {
qrow = append(qrow, types.QValueUInt8{Val: **v})
}
case *uint8:
qrow = append(qrow, types.QValueUInt8{Val: *v})
case **uint16:
if *v == nil {
qrow = append(qrow, types.QValueNull(types.QValueKindUInt16))
} else {
qrow = append(qrow, types.QValueUInt16{Val: **v})
}
case *uint16:
qrow = append(qrow, types.QValueUInt16{Val: *v})
case **uint32:
if *v == nil {
qrow = append(qrow, types.QValueNull(types.QValueKindUInt32))
} else {
qrow = append(qrow, types.QValueUInt32{Val: **v})
}
case *uint32:
qrow = append(qrow, types.QValueUInt32{Val: *v})
case **uint64:
if *v == nil {
qrow = append(qrow, types.QValueNull(types.QValueKindUInt64))
} else {
qrow = append(qrow, types.QValueUInt64{Val: **v})
}
case *uint64:
qrow = append(qrow, types.QValueUInt64{Val: *v})
case **big.Int:
if batch.Schema.Fields[idx].Type == types.QValueKindInt256 {
qrow = append(qrow, types.QValueInt256{Val: *v})
} else {
qrow = append(qrow, types.QValueUInt256{Val: *v})
}
case *time.Time:
qrow = append(qrow, types.QValueTimestamp{Val: *v})
case *time.Duration:
qrow = append(qrow, types.QValueTime{Val: *v})
case *[]time.Time:
qrow = append(qrow, types.QValueArrayTimestamp{Val: *v})
case **decimal.Decimal:
if *v == nil {
qrow = append(qrow, types.QValueNull(types.QValueKindNumeric))
} else {
qrow = append(qrow, types.QValueNumeric{Val: **v})
}
case *decimal.Decimal:
qrow = append(qrow, types.QValueNumeric{Val: *v})
case *[]decimal.Decimal:
qrow = append(qrow, types.QValueArrayNumeric{Val: *v})
case **bool:
if *v == nil {
qrow = append(qrow, types.QValueNull(types.QValueKindBoolean))
} else {
qrow = append(qrow, types.QValueBoolean{Val: **v})
}
case *bool:
qrow = append(qrow, types.QValueBoolean{Val: *v})
case **float32:
if *v == nil {
qrow = append(qrow, types.QValueNull(types.QValueKindFloat32))
} else {
qrow = append(qrow, types.QValueFloat32{Val: **v})
}
case *float32:
qrow = append(qrow, types.QValueFloat32{Val: *v})
case *[]float32:
qrow = append(qrow, types.QValueArrayFloat32{Val: *v})
case **float64:
if *v == nil {
qrow = append(qrow, types.QValueNull(types.QValueKindFloat64))
} else {
qrow = append(qrow, types.QValueFloat64{Val: **v})
}
case *float64:
qrow = append(qrow, types.QValueFloat64{Val: *v})
case *[]float64:
qrow = append(qrow, types.QValueArrayFloat64{Val: *v})
case *uuid.UUID:
qrow = append(qrow, types.QValueUUID{Val: *v})
case *[]uuid.UUID:
qrow = append(qrow, types.QValueArrayUUID{Val: *v})
case **chcol.JSON:
if *v == nil {
qrow = append(qrow, types.QValueNull(types.QValueKindJSON))
} else {
jsonb, err := (**v).MarshalJSON()
if err != nil {
return nil, err
}
qrow = append(qrow, types.QValueJSON{Val: string(jsonb)})
}
case *chcol.JSON:
jsonb, err := (*v).MarshalJSON()
if err != nil {
return nil, err
}
qrow = append(qrow, types.QValueJSON{Val: string(jsonb)})
default:
return nil, fmt.Errorf("cannot convert %T to types", v)
}
}
batch.Records = append(batch.Records, qrow)
}
return batch, rows.Err()
}
// CountNonDeletedRows returns the number of rows in table where _peerdb_is_deleted = 0.
// Unlike GetRows it does not use FINAL, so it works for engines that reject FINAL (e.g. MergeTree).
func (s ClickHouseSuite) CountNonDeletedRows(table string) (int, error) {
ch, err := connclickhouse.Connect(s.t.Context(), nil, s.Peer().GetClickhouseConfig())
if err != nil {
return 0, err
}
defer ch.Close()
var count uint64
err = ch.QueryRow(s.t.Context(),
fmt.Sprintf(`SELECT count() FROM "%s" WHERE _peerdb_is_deleted = 0 SETTINGS use_query_cache = false`, table),
).Scan(&count)
return int(count), err
}
func (s ClickHouseSuite) queryRawTable(conn clickhouse.Conn, table string, cols string) (driver.Rows, error) {
return conn.Query(
s.t.Context(),
fmt.Sprintf(`SELECT %s FROM "%s" ORDER BY 1 SETTINGS use_query_cache = false`, cols, table),
)
}
func SetupClickHouseSuite[TSource SuiteSource](
t *testing.T,
cluster bool,
setupSource func(*testing.T) (TSource, string, error),
) func(*testing.T) ClickHouseSuite {
t.Helper()
return func(t *testing.T) ClickHouseSuite {
t.Helper()
source, suffix, err := setupSource(t)
require.NoError(t, err, "failed to setup postgres")
s3Helper, err := NewS3TestHelper(t.Context(), Minio)
require.NoError(t, err, "failed to setup S3")
s := ClickHouseSuite{
t: t,
source: SuiteSource(source),
suffix: suffix,
s3Helper: s3Helper,
cluster: cluster,
}
ch, err := connclickhouse.Connect(t.Context(), nil, s.PeerForDatabase("default").GetClickhouseConfig())
require.NoError(t, err, "failed to connect to clickhouse")
if cluster {
err = ch.Exec(t.Context(), "CREATE DATABASE e2e_test_"+suffix+" ON CLUSTER cicluster")
} else {
err = ch.Exec(t.Context(), "CREATE DATABASE e2e_test_"+suffix)
}
require.NoError(t, err, "failed to create clickhouse database")
connector, err := connclickhouse.NewClickHouseConnector(t.Context(), nil, s.Peer().GetClickhouseConfig())
require.NoError(t, err)
s.connector = connector
catalogPool, err := internal.GetCatalogConnectionPoolFromEnv(t.Context())
require.NoError(t, err, "failed to get catalog connection pool")
s.catalog = catalogPool
return s
}
}