-
Notifications
You must be signed in to change notification settings - Fork 198
Expand file tree
/
Copy pathconversion_avro.go
More file actions
239 lines (207 loc) · 6.67 KB
/
Copy pathconversion_avro.go
File metadata and controls
239 lines (207 loc) · 6.67 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
package model
import (
"context"
"fmt"
"log/slog"
"strconv"
"sync/atomic"
"github.com/hamba/avro/v2"
"go.temporal.io/sdk/log"
"github.com/PeerDB-io/peerdb/flow/generated/protos"
"github.com/PeerDB-io/peerdb/flow/internal"
"github.com/PeerDB-io/peerdb/flow/model/qvalue"
"github.com/PeerDB-io/peerdb/flow/shared/types"
)
//nolint:govet // field alignment not worth readability cost
type QRecordAvroConverter struct {
logger log.Logger
Schema *QRecordAvroSchemaDefinition
ColNames []string
TargetDWH protos.DBType
UnboundedNumericAsString bool
NullMismatchTracker *NullMismatchTracker
}
func NewQRecordAvroConverter(
ctx context.Context,
env map[string]string,
schema *QRecordAvroSchemaDefinition,
targetDWH protos.DBType,
colNames []string,
logger log.Logger,
) (*QRecordAvroConverter, error) {
var unboundedNumericAsString bool
if targetDWH == protos.DBType_CLICKHOUSE {
var err error
unboundedNumericAsString, err = internal.PeerDBEnableClickHouseNumericAsString(ctx, env)
if err != nil {
return nil, err
}
}
return &QRecordAvroConverter{
Schema: schema,
TargetDWH: targetDWH,
ColNames: colNames,
logger: logger,
UnboundedNumericAsString: unboundedNumericAsString,
}, nil
}
func (qac *QRecordAvroConverter) Convert(
ctx context.Context,
env map[string]string,
qrecord []types.QValue,
typeConversions map[string]types.TypeConversion,
numericTruncator SnapshotTableNumericTruncator,
format internal.BinaryFormat,
calcSize bool,
) (map[string]any, int64, error) {
m := make(map[string]any, len(qrecord))
s := int64(0)
for idx, val := range qrecord {
if typeConversion, ok := typeConversions[qac.Schema.Fields[idx].Name]; ok {
val = typeConversion.ValueConversion(val)
}
// Record the cases where the value is null AND strict mode would say not nullable
if val.Value() == nil && qac.NullMismatchTracker != nil {
qac.NullMismatchTracker.RecordNull(idx)
}
avroVal, size, err := qvalue.QValueToAvro(
ctx, val,
&qac.Schema.Fields[idx], qac.TargetDWH, qac.logger, qac.UnboundedNumericAsString,
numericTruncator.Get(idx),
format,
calcSize,
)
if err != nil {
return nil, 0, fmt.Errorf("failed to convert QValue to Avro-compatible value: %w", err)
}
m[qac.ColNames[idx]] = avroVal
if calcSize {
s += size
}
}
return m, s, nil
}
type QRecordAvroField struct {
Type any `json:"type"`
Name string `json:"name"`
}
type QRecordAvroSchema struct {
Type string `json:"type"`
Name string `json:"name"`
Fields []QRecordAvroField `json:"fields"`
}
type QRecordAvroSchemaDefinition struct {
Schema *avro.RecordSchema
Fields []types.QField
}
type QRecordAvroChunkSizeTracker struct {
Bytes atomic.Int64
}
func GetAvroSchemaDefinition(
ctx context.Context,
env map[string]string,
dstTableName string,
qRecordSchema types.QRecordSchema,
targetDWH protos.DBType,
avroNameMap map[string]string,
) (*QRecordAvroSchemaDefinition, error) {
avroFields := make([]*avro.Field, 0, len(qRecordSchema.Fields))
namedSchemaSeen := make(map[string]avro.NamedSchema)
for _, qField := range qRecordSchema.Fields {
avroType, err := qvalue.GetAvroSchemaFromQValueKind(ctx, env, qField.Type, targetDWH, qField.Precision, qField.Scale)
if err != nil {
return nil, err
}
// Avro named types (fixed, enum, record) must only be defined once per schema;
// subsequent references use RefSchema to emit just the type name.
if named, ok := avroType.(avro.NamedSchema); ok {
if _, seen := namedSchemaSeen[named.FullName()]; seen {
avroType = avro.NewRefSchema(named)
} else {
namedSchemaSeen[named.FullName()] = named
}
}
if qField.Nullable {
avroType, err = qvalue.NullableAvroSchema(avroType)
if err != nil {
return nil, err
}
}
avroFieldName := qField.Name
if avroNameMap != nil {
avroFieldName = avroNameMap[qField.Name]
}
avroField, err := avro.NewField(avroFieldName, avroType)
if err != nil {
return nil, err
}
avroFields = append(avroFields, avroField)
}
if targetDWH == protos.DBType_CLICKHOUSE {
dstTableName = qvalue.ConvertToAvroCompatibleName(dstTableName)
}
avroSchema, err := avro.NewRecordSchema(dstTableName, "", avroFields)
if err != nil {
return nil, err
}
return &QRecordAvroSchemaDefinition{
Schema: avroSchema,
Fields: qRecordSchema.Fields,
}, nil
}
func ConstructColumnNameAvroFieldMap(fields []types.QField) map[string]string {
m := make(map[string]string, len(fields))
for i, field := range fields {
m[field.Name] = qvalue.ConvertToAvroCompatibleName(field.Name) + "_" + strconv.FormatInt(int64(i), 10)
}
return m
}
// NullMismatchTracker detects null values in columns that would be non-nullable under strict mode
type NullMismatchTracker struct {
schemaDebug *types.NullableSchemaDebug
mismatchedCols []bool
}
func NewNullMismatchTracker(
schemaDebug *types.NullableSchemaDebug,
) *NullMismatchTracker {
if schemaDebug == nil {
return nil // Not in lax mode
}
return &NullMismatchTracker{
schemaDebug: schemaDebug,
mismatchedCols: make([]bool, len(schemaDebug.StrictNullable)),
}
}
func (t *NullMismatchTracker) RecordNull(fieldIdx int) {
if fieldIdx < len(t.schemaDebug.StrictNullable) && !t.schemaDebug.StrictNullable[fieldIdx] {
t.mismatchedCols[fieldIdx] = true
}
}
func (t *NullMismatchTracker) LogIfMismatch(ctx context.Context, logger log.Logger) {
// Categorize mismatched columns by the reason they were marked non-nullable
var lookupFailedCols []string // pg_attribute lookup failed (table OID or attnum mismatch)
var notNullInPgCols []string // Found in pg_attribute but marked NOT NULL
for idx, mismatched := range t.mismatchedCols {
if !mismatched || idx >= len(t.schemaDebug.PgxFields) {
continue
}
colName := t.schemaDebug.PgxFields[idx].Name
if idx < len(t.schemaDebug.MatchFound) && !t.schemaDebug.MatchFound[idx] {
lookupFailedCols = append(lookupFailedCols, colName)
} else {
notNullInPgCols = append(notNullInPgCols, colName)
}
}
if len(lookupFailedCols) == 0 && len(notNullInPgCols) == 0 {
return
}
// Dump the ENTIRE schema debug info - all pgx fields, pg_attribute rows, and table metadata
logger.Warn("Null values in columns that would be non-nullable under strict mode",
slog.Any("lookup_failed_columns", lookupFailedCols),
slog.Any("not_null_in_pg_attribute_columns", notNullInPgCols),
slog.Any("queried_table_oids", t.schemaDebug.QueriedTableOIDs),
slog.Any("pgx_field_descriptions", t.schemaDebug.PgxFields),
slog.Any("pg_attribute_rows", t.schemaDebug.PgAttributeRows),
slog.Any("tables_with_inheritance", t.schemaDebug.Tables),
)
}