Skip to content

Conversation

@mafredri
Copy link
Member

@mafredri mafredri commented Oct 29, 2025

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.

Go installable branch: https://github.com/coder/sqlc/tree/mafredri/fix-ambiguous-column.import

CGO_ENABLED=1 go install github.com/coder/sqlc/cmd/sqlc@aab4e865a51df0c43e1839f81a9d349b41d14f05

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.


Upstream sqlc-dev#4159

mafredri added a commit to coder/coder that referenced this pull request Oct 29, 2025
mafredri added a commit to coder/coder that referenced this pull request Oct 29, 2025
@mafredri mafredri force-pushed the mafredri/fix-ambiguous-column branch 5 times, most recently from 5f67321 to 7c1a82b Compare October 29, 2025 12:09
mafredri added a commit to coder/coder that referenced this pull request Oct 29, 2025
mafredri added a commit to coder/coder that referenced this pull request Oct 29, 2025
)
SELECT *
FROM wtask
ORDER BY CASE WHEN w_owner_id = @owner_id THEN 0 ELSE 1 END;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: Why didn't I just use this workaround?

Because the CTE wasn't indexed and as such, unknown column w_owner_id.

mafredri added a commit to coder/coder that referenced this pull request Oct 29, 2025
mafredri added a commit to coder/coder that referenced this pull request Oct 29, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant