sqlc icon indicating copy to clipboard operation
sqlc copied to clipboard

Table alias does not exist for subquery

Open waterfountain1996 opened this issue 1 year ago • 2 comments

Version

1.27.0

What happened?

SQLC fails to generate a query where I try to use a column from a subquery in a WHERE clause to compare against a query argument, which is a valid SQL syntax for SQLite. The same query compiles successfully I use a literal value instead of an argument.

P.S. I've tried reproducing it in the playground and it seems that it actually compiles successfully on v1.25.0 but not on v1.26 or newer.

Relevant log output

# package db
queries.sql:7:7: table alias "a" does not exist

Database schema

CREATE TABLE posts (
  id   BIGSERIAL PRIMARY KEY,
  tags TEXT -- JSON array of hashtags like ["#foo", "#bar"]
);

SQL queries

-- name: GetPostIDsByTag :many
SELECT DISTINCT a.id
FROM (
	SELECT p.id, ltrim(json_each.value ->> '$.name', '#') AS tag
	FROM posts p, json_each(p.tags)
) a
WHERE a.tag = 'foo';

Configuration

{
  "version": "2",
  "sql": [{
    "schema": "schema.sql",
    "queries": "query.sql",
    "engine": "sqlite",
    "gen": {
      "go": {
        "out": "db"
      }
    }
  }]
}

Playground URL

https://play.sqlc.dev/p/33831f5ac4e36ae1654164ae929c04ed981a51b135d20aca35e492573f00c8b0

What operating system are you using?

macOS

What database engines are you using?

SQLite

What type of code are you generating?

Go

waterfountain1996 avatar Oct 07 '24 17:10 waterfountain1996

A simplified version of the query above

SELECT DISTINCT p.id
FROM posts p, json_each(p.tags) j
WHERE ltrim(j.value ->> '$.name', '#') = ?

gives the same table alias "j" does not exist error.

waterfountain1996 avatar Oct 07 '24 17:10 waterfountain1996

I'm getting a similar issue:

SELECT 
    things,
    bool_and(bool_things)
FROM (
    SELECT things, bool_things FROM some_things
    UNION
    SELECT things, bool_things FROM other_things
) AS x
WHERE x.things = $1
GROUP BY x.things;

The above query results in the following error: table alias "x" does not exist

eattoe-ctoken avatar Apr 23 '25 12:04 eattoe-ctoken