Skip to content

Commit 308583e

Browse files
kyleconroyrollulus
andauthored
codegen(go): Strip invalid characters from table and column names (#2314)
* fix: Let column names not result in invalid Go field names Column names are less restricted than Go struct field names, which should be proper Go identifiers. Hence, column names cannot be translated directly into field names. This commit tries to address this. Characters in column names that do not qualify as a Go identifier are stripped. The title casing as applied to underscores is applied to stripped characters. * test: Add updated tests --------- Co-authored-by: Rollulus <rollulus@xs4all.nl>
1 parent d37c9d4 commit 308583e

File tree

7 files changed

+97
-6
lines changed

7 files changed

+97
-6
lines changed

internal/codegen/golang/struct.go

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,18 @@ func StructName(name string, settings *plugin.Settings) string {
1919
if rename := settings.Rename[name]; rename != "" {
2020
return rename
2121
}
22-
var (
23-
out string
24-
fn = func(r rune) bool {
25-
return r == '_' || r == '-'
22+
out := ""
23+
name = strings.Map(func(r rune) rune {
24+
if unicode.IsLetter(r) {
25+
return r
2626
}
27-
)
28-
for _, p := range strings.FieldsFunc(name, fn) {
27+
if unicode.IsDigit(r) {
28+
return r
29+
}
30+
return rune('_')
31+
}, name)
32+
33+
for _, p := range strings.Split(name, "_") {
2934
if p == "id" {
3035
out += "ID"
3136
} else {
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
This tests that Go struct field names are proper Go identifiers.

internal/endtoend/testdata/codegen_struct_field_names/stdlib/go/db.go

Lines changed: 31 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

internal/endtoend/testdata/codegen_struct_field_names/stdlib/go/models.go

Lines changed: 15 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

internal/endtoend/testdata/codegen_struct_field_names/stdlib/go/query.sql.go

Lines changed: 21 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
CREATE TABLE bar (
2+
id INT NOT NULL,
3+
"!!!nobody,_,-would-believe---this-...?!" INT,
4+
"parent id" INT);
5+
6+
-- name: test :one
7+
SELECT * from bar limit 1;
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"version": "1",
3+
"packages": [
4+
{
5+
"path": "go",
6+
"name": "querytest",
7+
"schema": "query.sql",
8+
"queries": "query.sql"
9+
}
10+
]
11+
}

0 commit comments

Comments
 (0)