Skip to content

Commit 92560b8

Browse files
committed
compiler: report an error for an unknown relation in rel.* function arguments
1 parent 3ad8b20 commit 92560b8

21 files changed

Lines changed: 290 additions & 3 deletions

File tree

‎internal/compiler/output_columns.go‎

Lines changed: 81 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,13 @@ func (c *Compiler) outputColumns(qc *QueryCatalog, node ast.Node) ([]*Column, er
320320
if res.Name != nil {
321321
name = *res.Name
322322
}
323+
if n.Args != nil {
324+
for _, arg := range n.Args.Items {
325+
if err := checkStarRelation(qc, node, arg, tables, rtables); err != nil {
326+
return nil, err
327+
}
328+
}
329+
}
323330
fun, err := qc.catalog.ResolveFuncCall(n)
324331
if err == nil {
325332
cols = append(cols, &Column{
@@ -345,7 +352,7 @@ func (c *Compiler) outputColumns(qc *QueryCatalog, node ast.Node) ([]*Column, er
345352
case ast.EXISTS_SUBLINK:
346353
cols = append(cols, &Column{Name: name, DataType: "bool", NotNull: true})
347354
case ast.EXPR_SUBLINK:
348-
subcols, err := c.outputColumns(qc, n.Subselect)
355+
subcols, err := c.subqueryOutputColumns(qc, n.Subselect, tables)
349356
if err != nil {
350357
return nil, err
351358
}
@@ -381,7 +388,7 @@ func (c *Compiler) outputColumns(qc *QueryCatalog, node ast.Node) ([]*Column, er
381388
cols = append(cols, col)
382389

383390
case *ast.SelectStmt:
384-
subcols, err := c.outputColumns(qc, n)
391+
subcols, err := c.subqueryOutputColumns(qc, n, tables)
385392
if err != nil {
386393
return nil, err
387394
}
@@ -610,7 +617,7 @@ func (c *Compiler) sourceTables(qc *QueryCatalog, node ast.Node) ([]*Table, erro
610617
tables = append(tables, table)
611618

612619
case *ast.RangeSubselect:
613-
cols, err := c.outputColumns(qc, n.Subquery)
620+
cols, err := c.subqueryOutputColumns(qc, n.Subquery, tables)
614621
if err != nil {
615622
return nil, err
616623
}
@@ -658,6 +665,77 @@ func (c *Compiler) sourceTables(qc *QueryCatalog, node ast.Node) ([]*Table, erro
658665
return tables, nil
659666
}
660667

668+
// subqueryOutputColumns computes the output columns of a nested statement.
669+
// The relations of the enclosing statement stay visible to it, because a
670+
// correlated subquery may refer to them.
671+
func (c *Compiler) subqueryOutputColumns(qc *QueryCatalog, node ast.Node, outer []*Table) ([]*Column, error) {
672+
saved := qc.outer
673+
qc.outer = append(append([]*Table{}, saved...), outer...)
674+
defer func() { qc.outer = saved }()
675+
return c.outputColumns(qc, node)
676+
}
677+
678+
// fromNameVisitor collects the names that FROM items of a statement can be
679+
// referred to by, including set-returning functions that sqlc cannot resolve
680+
// and therefore does not register as tables.
681+
type fromNameVisitor struct {
682+
names map[string]struct{}
683+
}
684+
685+
func (v *fromNameVisitor) Visit(n ast.Node) astutils.Visitor {
686+
var alias *ast.Alias
687+
switch n := n.(type) {
688+
case *ast.RangeVar:
689+
alias = n.Alias
690+
if alias == nil && n.Relname != nil {
691+
v.names[*n.Relname] = struct{}{}
692+
}
693+
case *ast.RangeFunction:
694+
alias = n.Alias
695+
case *ast.RangeSubselect:
696+
alias = n.Alias
697+
}
698+
if alias != nil && alias.Aliasname != nil {
699+
v.names[*alias.Aliasname] = struct{}{}
700+
}
701+
return v
702+
}
703+
704+
// checkStarRelation returns an error when arg is a qualified star such as
705+
// "whatever.*" and the qualifier does not name a relation in scope. It
706+
// reports the same error as other references to an unknown table alias.
707+
func checkStarRelation(qc *QueryCatalog, node, arg ast.Node, tables, rtables []*Table) error {
708+
ref, ok := arg.(*ast.ColumnRef)
709+
if !ok || !hasStarRef(ref) {
710+
return nil
711+
}
712+
parts := stringSlice(ref.Fields)
713+
if len(parts) != 1 {
714+
return nil
715+
}
716+
scope := parts[0]
717+
for _, list := range [][]*Table{tables, qc.outer} {
718+
for _, t := range list {
719+
if t.Rel != nil && t.Rel.Name == scope {
720+
return nil
721+
}
722+
}
723+
}
724+
if returningTableForScope(tables, rtables, scope) != nil {
725+
return nil
726+
}
727+
v := &fromNameVisitor{names: map[string]struct{}{}}
728+
astutils.Walk(v, node)
729+
if _, ok := v.names[scope]; ok {
730+
return nil
731+
}
732+
return &sqlerr.Error{
733+
Code: "42703",
734+
Message: fmt.Sprintf("table alias %q does not exist", scope),
735+
Location: ref.Location,
736+
}
737+
}
738+
661739
func outputColumnRefs(res *ast.ResTarget, tables []*Table, node *ast.ColumnRef) ([]*Column, error) {
662740
parts := stringSlice(node.Fields)
663741
var schema, name, alias string

‎internal/compiler/query_catalog.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ type QueryCatalog struct {
1212
catalog *catalog.Catalog
1313
ctes map[string]*Table
1414
embeds preprocess.EmbedSet
15+
16+
// outer holds the relations of the enclosing statements while the output
17+
// columns of a nested statement are computed.
18+
outer []*Table
1519
}
1620

1721
func (comp *Compiler) buildQueryCatalog(c *catalog.Catalog, node ast.Node, embeds preprocess.EmbedSet) (*QueryCatalog, error) {
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"contexts": ["base"]
3+
}

‎internal/endtoend/testdata/agg_correlated_subquery/postgresql/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/agg_correlated_subquery/postgresql/go/models.go‎

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

‎internal/endtoend/testdata/agg_correlated_subquery/postgresql/go/query.sql.go‎

Lines changed: 37 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
-- name: Correlated :many
2+
SELECT (SELECT ARRAY_AGG(o.*) FROM b) FROM o;
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
CREATE TABLE o (
2+
x INT NOT NULL
3+
);
4+
5+
CREATE TABLE b (
6+
x INT NOT NULL
7+
);
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"version": "1",
3+
"packages": [
4+
{
5+
"path": "go",
6+
"engine": "postgresql",
7+
"name": "querytest",
8+
"schema": "schema.sql",
9+
"queries": "query.sql"
10+
}
11+
]
12+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
-- name: BugDemo :exec
2+
SELECT id, ARRAY_AGG(whatever.*) FROM worker;

0 commit comments

Comments
 (0)