sqlc icon indicating copy to clipboard operation
sqlc copied to clipboard

Track scope for CTEs to fix ambiguous column bug

Open mafredri opened this issue 1 month ago • 0 comments

EDIT: Sorry, I did not intend to open this PR over here yet, it was meant for coder/sqlc. But since it's here already. I'll keep it open.


While adding a simple EXISTS condition, I ran into an sqlc bug because it wasn't tracking scope for CTEs.

query.sql:11:20: column reference "owner_id" is ambiguous
query.sql:24:20: column "w_owner_id" does not exist
query.sql:38:20: column reference "owner_id" is ambiguous

The query could look something like this:

WITH cte AS (
	SELECT owner_id
	FROM table_with_owner_id
	WHERE EXISTS (SELECT 1 FROM another_table_with_owner_id)
)
SELECT * FROM cte;

Test queries have been added that reproduce the bug.

Some of the existing testdata also had to be updated because the tracking got improved.


This bug was initially solved via Coder Tasks (Claude Code), but the solution was messy and followed the "throw code at it until it works", as such it has been mostly rewritten.

mafredri avatar Oct 29 '25 09:10 mafredri