Skip to content

Commit 734b4b3

Browse files
authored
fix(compiler): Validate table alias references (#1283)
1 parent fd81da8 commit 734b4b3

File tree

7 files changed

+61
-0
lines changed

7 files changed

+61
-0
lines changed

internal/compiler/resolve.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,11 +147,20 @@ func resolveCatalogRefs(c *catalog.Catalog, qc *QueryCatalog, rvs []*ast.RangeVa
147147
if original, ok := aliasMap[alias]; ok {
148148
search = []*ast.TableName{original}
149149
} else {
150+
var located bool
150151
for _, fqn := range tables {
151152
if fqn.Name == alias {
153+
located = true
152154
search = []*ast.TableName{fqn}
153155
}
154156
}
157+
if !located {
158+
return nil, &sqlerr.Error{
159+
Code: "42703",
160+
Message: fmt.Sprintf("table alias \"%s\" does not exist", alias),
161+
Location: left.Location,
162+
}
163+
}
155164
}
156165
}
157166

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
-- https://github.com/kyleconroy/sqlc/issues/437
2+
CREATE TABLE authors (
3+
id INT PRIMARY KEY,
4+
name VARCHAR(255) NOT NULL,
5+
bio text
6+
);
7+
8+
-- name: GetAuthor :one
9+
SELECT *
10+
FROM authors a
11+
WHERE p.id = ?
12+
LIMIT 1;
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": "mysql",
7+
"name": "querytest",
8+
"schema": "query.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+
# package querytest
2+
query.sql:9:1: table alias "p" does not exist
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
-- https://github.com/kyleconroy/sqlc/issues/437
2+
CREATE TABLE authors (
3+
id BIGSERIAL PRIMARY KEY,
4+
name text NOT NULL,
5+
bio text
6+
);
7+
8+
-- name: GetAuthor :one
9+
SELECT *
10+
FROM authors a
11+
WHERE p.id = $1
12+
LIMIT 1;
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": "query.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+
# package querytest
2+
query.sql:11:9: table alias "p" does not exist

0 commit comments

Comments
 (0)