Skip to content

Commit 69593d1

Browse files
authored
fix(postgresql): Add quotes for CamelCase columns (#1729)
If columns are created with CamelCase, they have to be quoted or else postgres won't find them.
1 parent 9f6a6a7 commit 69593d1

File tree

4 files changed

+47
-3
lines changed

4 files changed

+47
-3
lines changed

internal/compiler/compile_test.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package compiler
2+
3+
import (
4+
"testing"
5+
6+
"github.com/kyleconroy/sqlc/internal/config"
7+
)
8+
9+
func TestQuoteIdent(t *testing.T) {
10+
type test struct {
11+
engine config.Engine
12+
in string
13+
want string
14+
}
15+
tests := []test{
16+
{config.EnginePostgreSQL, "age", "age"},
17+
{config.EnginePostgreSQL, "Age", `"Age"`},
18+
{config.EnginePostgreSQL, "CamelCase", `"CamelCase"`},
19+
{config.EngineMySQL, "CamelCase", "CamelCase"},
20+
// keywords
21+
{config.EnginePostgreSQL, "select", `"select"`},
22+
{config.EngineMySQL, "select", "`select`"},
23+
}
24+
25+
for _, spec := range tests {
26+
compiler := NewCompiler(config.SQL{
27+
Engine: spec.engine,
28+
}, config.CombinedSettings{})
29+
30+
t.Run(spec.in, func(t *testing.T) {
31+
got := compiler.quoteIdent(spec.in)
32+
if got != spec.want {
33+
t.Error("quoteIdent: engine " + string(spec.engine) + " failed for " + spec.in + ", want " + spec.want + ", got " + got)
34+
}
35+
})
36+
}
37+
38+
}

internal/compiler/expand.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,12 @@ func (c *Compiler) quoteIdent(ident string) string {
4545
return "\"" + ident + "\""
4646
}
4747
}
48+
if c.conf.Engine == config.EnginePostgreSQL {
49+
// camelCase means the column is also camelCase
50+
if strings.ToLower(ident) != ident {
51+
return "\"" + ident + "\""
52+
}
53+
}
4854
return ident
4955
}
5056

internal/endtoend/testdata/select_star/postgresql/stdlib/go/query.sql.go

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
CREATE TABLE users (
2-
id integer NOT NULL PRIMARY KEY,
2+
ID integer NOT NULL PRIMARY KEY,
33
first_name varchar(255) NOT NULL,
44
last_name varchar(255),
5-
age integer NOT NULL
5+
"Age" integer NOT NULL
66
);

0 commit comments

Comments
 (0)