Skip to content

Commit d5aa1c5

Browse files
committed
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.
1 parent 0ebe855 commit d5aa1c5

File tree

7 files changed

+95
-0
lines changed

7 files changed

+95
-0
lines changed

internal/codegen/golang/struct.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,15 @@ func StructName(name string, settings *plugin.Settings) string {
2020
return rename
2121
}
2222
out := ""
23+
name = strings.Map(func(r rune) rune {
24+
if unicode.IsLetter(r) {
25+
return r
26+
}
27+
if unicode.IsDigit(r) {
28+
return r
29+
}
30+
return rune('_')
31+
}, name)
2332
for _, p := range strings.Split(name, "_") {
2433
if p == "id" {
2534
out += "ID"
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)