Skip to content

Commit 6ee98f0

Browse files
authored
parser: Add support for mathmatical operators (#132)
Also, don't leave out expressions we haven't added. Instead, generate a column with an "any" type.
1 parent 6da56ff commit 6ee98f0

File tree

3 files changed

+46
-1
lines changed

3 files changed

+46
-1
lines changed

internal/dinosql/parser.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,7 @@ func parseQuery(c core.Catalog, stmt nodes.Node, source string) (*Query, error)
379379
default:
380380
return nil, nil
381381
}
382+
382383
rawSQL, err := pluckQuery(source, raw)
383384
if err != nil {
384385
return nil, err
@@ -562,9 +563,15 @@ func outputColumns(c core.Catalog, node nodes.Node) ([]core.Column, error) {
562563
if res.Name != nil {
563564
name = *res.Name
564565
}
565-
if postgres.IsComparisonOperator(join(n.Name, "")) {
566+
switch {
567+
case postgres.IsComparisonOperator(join(n.Name, "")):
566568
// TODO: Generate a name for these operations
567569
cols = append(cols, core.Column{Name: name, DataType: "bool", NotNull: true})
570+
case postgres.IsMathematicalOperator(join(n.Name, "")):
571+
// TODO: Generate correct numeric type
572+
cols = append(cols, core.Column{Name: name, DataType: "pg_catalog.int4", NotNull: true})
573+
default:
574+
cols = append(cols, core.Column{Name: name, DataType: "any", NotNull: false})
568575
}
569576

570577
case nodes.CoalesceExpr:

internal/dinosql/query_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -690,6 +690,19 @@ func TestQueries(t *testing.T) {
690690
},
691691
},
692692
},
693+
{
694+
"mathmatical-operator",
695+
`
696+
CREATE TABLE foo (num integer not null);
697+
SELECT *, num / 1024 as division FROM foo;
698+
`,
699+
Query{
700+
Columns: []core.Column{
701+
{Name: "num", DataType: "pg_catalog.int4", NotNull: true, Table: public("foo")},
702+
{Name: "division", DataType: "pg_catalog.int4", NotNull: true},
703+
},
704+
},
705+
},
693706
} {
694707
test := tc
695708
t.Run(test.name, func(t *testing.T) {

internal/postgres/types.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,28 @@ func IsComparisonOperator(s string) bool {
1414
}
1515
return true
1616
}
17+
18+
func IsMathematicalOperator(s string) bool {
19+
switch s {
20+
case "+":
21+
case "-":
22+
case "*":
23+
case "/":
24+
case "%":
25+
case "^":
26+
case "|/":
27+
case "||/":
28+
case "!":
29+
case "!!":
30+
case "@":
31+
case "&":
32+
case "|":
33+
case "#":
34+
case "~":
35+
case "<<":
36+
case ">>":
37+
default:
38+
return false
39+
}
40+
return true
41+
}

0 commit comments

Comments
 (0)