Skip to content

Track scope for CTEs to fix ambiguous column bug - #1

Merged
mafredri merged 2 commits into
mainfrom
mafredri/fix-ambiguous-column
Nov 13, 2026
Merged

mafredri merged 2 commits into
mainfrom
mafredri/fix-ambiguous-column

Conversation

@mafredri

@mafredri mafredri commented Oct 29, 2025 •

Copy link
Copy Markdown
Member

sqlc does not track scope for CTEs. A subquery inside a CTE makes column references in the CTE, and in CTEs that select from it, resolve against the subquery's tables too, so valid queries fail to generate:

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

A minimal shape that triggers it:

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

This change tracks the CTE a column reference belongs to when resolving columns and parameters. The new cte_ambiguous_column testdata reproduces the errors above. Parameters inside a CTE, or compared against a CTE column, now get the referenced type instead of a nullable fallback: cte_left_join generates name string (was dollar_1 pgtype.Text), and cte_update generates bool, string, int64 (was pgtype.Bool, pgtype.Text, pgtype.Int8).

main never had this fix. The fork was pinned to the side branch mafredri/fix-ambiguous-column.import, and #6 merged upstream v1.31.1 into main without it. This branch is the fix applied to main (337309bf), with the new testdata regenerated for the v1.31.1 version stamp.

go test ./... against PostgreSQL 16 fails the same tests on main and on this branch: TestReplay/{base,managed-db}/wasm_plugin_sqlc_gen_unsafe_paths. Its expected error path depends on where the repository is checked out.

Upstream: sqlc-dev#4159

🤖 Created with the help of Coder Agents.

)
SELECT *
FROM wtask
ORDER BY CASE WHEN w_owner_id = @owner_id THEN 0 ELSE 1 END;

Copy link
Copy Markdown
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
@mafredri
mafredri force-pushed the mafredri/fix-ambiguous-column branch from 7c1a82b to 7a30c2e Compare November 13, 2026 17:10
@mafredri
mafredri merged commit fb627c9 into main Nov 13, 2026
11 of 12 checks passed
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