sqlc-dev / sqlc

Generate type-safe code from SQL
https://sqlc.dev
MIT License
13.54k stars 809 forks source link

Table alias does not exist for subquery #3639

Open waterfountain1996 opened 1 month ago

waterfountain1996 commented 1 month ago

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 commented 1 month ago

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.