sqlc-dev/sqlc

Table alias does not exist for subquery

waterfountain1996 opened this issue · 1 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

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.