Skip to content

Commit 01e6649

Browse files
authored
fix: TransformWithStruct/DefaultNameTransformer change for invalid column names (#820)
Closes cloudquery/cloudquery#10274 I went for the simple approach of not accepting the json tag value if it's going to result in an invalid column name.
1 parent e9f29ff commit 01e6649

File tree

3 files changed

+29
-3
lines changed

3 files changed

+29
-3
lines changed

schema/table.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -360,8 +360,7 @@ func (t *Table) ValidateDuplicateColumns() error {
360360

361361
func (t *Table) ValidateColumnNames() error {
362362
for _, c := range t.Columns {
363-
ok := reValidColumnName.MatchString(c.Name)
364-
if !ok {
363+
if !ValidColumnName(c.Name) {
365364
return fmt.Errorf("column name %q on table %q is not valid: column names must contain only lower-case letters, numbers and underscores, and must start with a lower-case letter or underscore", c.Name, t.Name)
366365
}
367366
}
@@ -430,3 +429,7 @@ func (t *Table) Copy(parent *Table) *Table {
430429
}
431430
return &c
432431
}
432+
433+
func ValidColumnName(name string) bool {
434+
return reValidColumnName.MatchString(name)
435+
}

transformers/struct.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -363,7 +363,9 @@ func DefaultNameTransformer(field reflect.StructField) (string, error) {
363363
if jsonTag == "-" {
364364
return "", nil
365365
}
366-
name = jsonTag
366+
if schema.ValidColumnName(jsonTag) {
367+
name = jsonTag
368+
}
367369
}
368370
return defaultCaser.ToSnake(name), nil
369371
}

transformers/struct_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,10 @@ type (
6666
Name string `json:"name"`
6767
Version int `json:"version"`
6868
}
69+
70+
testFunnyStruct struct {
71+
AFunnyLookingField string `json:"OS-EXT:a-funny-looking-field"`
72+
}
6973
)
7074

7175
var (
@@ -243,6 +247,16 @@ var (
243247
},
244248
},
245249
}
250+
251+
expectedFunnyTable = schema.Table{
252+
Name: "test_funny_struct",
253+
Columns: schema.ColumnList{
254+
{
255+
Name: "a_funny_looking_field",
256+
Type: schema.TypeString,
257+
},
258+
},
259+
}
246260
)
247261

248262
func TestTableFromGoStruct(t *testing.T) {
@@ -356,6 +370,13 @@ func TestTableFromGoStruct(t *testing.T) {
356370
want: expectedTableWithPKs,
357371
wantErr: true,
358372
},
373+
{
374+
name: "Should properly transform structs with funny looking fields",
375+
args: args{
376+
testStruct: testFunnyStruct{},
377+
},
378+
want: expectedFunnyTable,
379+
},
359380
}
360381

361382
for _, tt := range tests {

0 commit comments

Comments
 (0)