Skip to content

Commit 15294de

Browse files
authored
parser: Add support for simple case expressions (#134)
* parser: Add support for simple case expressions More complex case expressions will generate columns with the `any` type
1 parent 6ee98f0 commit 15294de

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

internal/dinosql/parser.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -574,6 +574,31 @@ func outputColumns(c core.Catalog, node nodes.Node) ([]core.Column, error) {
574574
cols = append(cols, core.Column{Name: name, DataType: "any", NotNull: false})
575575
}
576576

577+
case nodes.CaseExpr:
578+
name := ""
579+
if res.Name != nil {
580+
name = *res.Name
581+
}
582+
// TODO: The TypeCase code has been copied from below. Instead, we need a recurse function to get the type of a node.
583+
if tc, ok := n.Defresult.(nodes.TypeCast); ok {
584+
if tc.TypeName == nil {
585+
return nil, errors.New("no type name type cast")
586+
}
587+
name := ""
588+
if ref, ok := tc.Arg.(nodes.ColumnRef); ok {
589+
name = join(ref.Fields, "_")
590+
}
591+
if res.Name != nil {
592+
name = *res.Name
593+
}
594+
// TODO Validate column names
595+
col := catalog.ToColumn(tc.TypeName)
596+
col.Name = name
597+
cols = append(cols, col)
598+
} else {
599+
cols = append(cols, core.Column{Name: name, DataType: "any", NotNull: false})
600+
}
601+
577602
case nodes.CoalesceExpr:
578603
for _, arg := range n.Args.Items {
579604
if ref, ok := arg.(nodes.ColumnRef); ok {
@@ -652,6 +677,14 @@ func outputColumns(c core.Catalog, node nodes.Node) ([]core.Column, error) {
652677
col := catalog.ToColumn(n.TypeName)
653678
col.Name = name
654679
cols = append(cols, col)
680+
681+
default:
682+
name := ""
683+
if res.Name != nil {
684+
name = *res.Name
685+
}
686+
cols = append(cols, core.Column{Name: name, DataType: "any", NotNull: false})
687+
655688
}
656689
}
657690
return cols, nil

internal/dinosql/query_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -703,6 +703,25 @@ func TestQueries(t *testing.T) {
703703
},
704704
},
705705
},
706+
{
707+
"case-stmt-bool",
708+
`
709+
CREATE TABLE foo (id text not null);
710+
SELECT CASE
711+
WHEN id = $1 THEN true
712+
ELSE false
713+
END is_one
714+
FROM foo;
715+
`,
716+
Query{
717+
Params: []Parameter{
718+
{1, core.Column{Table: public("foo"), Name: "id", DataType: "text", NotNull: true}},
719+
},
720+
Columns: []core.Column{
721+
{Name: "is_one", DataType: "pg_catalog.bool", NotNull: true},
722+
},
723+
},
724+
},
706725
} {
707726
test := tc
708727
t.Run(test.name, func(t *testing.T) {

0 commit comments

Comments
 (0)