Skip to content

Commit 9ede3a4

Browse files
authored
internal/parser: Support joins with aliases (#326)
1 parent 91fab73 commit 9ede3a4

6 files changed

Lines changed: 164 additions & 1 deletion

File tree

internal/dinosql/parser.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -576,19 +576,31 @@ func expandStmt(qc *QueryCatalog, raw nodes.RawStmt, node nodes.Node) ([]edit, e
576576
return nil, fmt.Errorf("unknown field in ColumnRef: %T", f)
577577
}
578578
}
579+
scope := join(ref.Fields, ".")
580+
counts := map[string]int{}
581+
if scope == "" {
582+
for _, t := range tables {
583+
for _, c := range t.Columns {
584+
counts[c.Name] += 1
585+
}
586+
}
587+
}
579588
for _, t := range tables {
580-
scope := join(ref.Fields, ".")
581589
if scope != "" && scope != t.Name {
582590
continue
583591
}
584592
for _, c := range t.Columns {
593+
fmt.Println(c.Name)
585594
cname := c.Name
586595
if res.Name != nil {
587596
cname = *res.Name
588597
}
589598
if scope != "" {
590599
cname = scope + "." + cname
591600
}
601+
if counts[cname] > 1 {
602+
cname = t.Name + "." + cname
603+
}
592604
if postgres.IsReservedKeyword(cname) {
593605
cname = "\"" + cname + "\""
594606
}
@@ -726,6 +738,9 @@ func sourceTables(qc *QueryCatalog, node nodes.Node) ([]core.Table, error) {
726738
cerr.Location = n.Location
727739
return nil, *cerr
728740
}
741+
if n.Alias != nil {
742+
table.Name = *n.Alias.Aliasname
743+
}
729744
tables = append(tables, table)
730745
default:
731746
return nil, fmt.Errorf("sourceTable: unsupported list item type: %T", n)

internal/endtoend/testdata/join_alias/go/db.go

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

internal/endtoend/testdata/join_alias/go/models.go

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

internal/endtoend/testdata/join_alias/go/query.sql.go

Lines changed: 80 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
CREATE TABLE foo (id serial not null);
2+
CREATE TABLE bar (id serial not null references foo(id), title text);
3+
4+
-- name: AliasJoin :many
5+
SELECT f.id, b.title
6+
FROM foo f
7+
JOIN bar b ON b.id = f.id
8+
WHERE f.id = $1;
9+
10+
-- name: AliasExpand :many
11+
SELECT *
12+
FROM foo f
13+
JOIN bar b ON b.id = f.id
14+
WHERE f.id = $1;
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"version": "1",
3+
"packages": [{
4+
"path": "go",
5+
"name": "querytest",
6+
"schema": "query.sql",
7+
"queries": "query.sql"
8+
}]
9+
}

0 commit comments

Comments
 (0)