Skip to content

Fix CTE AS normalization with alias removal - #112

Open
joelmarcotte wants to merge 2 commits into
mainfrom
joel.marcotte/cte-normalization
Open

joelmarcotte wants to merge 2 commits into
mainfrom
joel.marcotte/cte-normalization

Conversation

@joelmarcotte

@joelmarcotte joelmarcotte commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Preserve AS in PostgreSQL CTE headers, including MATERIALIZED and NOT MATERIALIZED forms.
  • Continue removing projection and table aliases when alias retention is disabled.
  • Cover multiple, recursive, nested, and column-list CTEs.
  • Keep up to four CTE frames inline to avoid allocations on common nested queries.

Validation

  • go test ./... -count=1
  • git diff --check

Performance

On Apple M5 Pro with Go 1.27.1, go test -run '^$' -bench '^BenchmarkCTENormalization$' -benchtime=300ms -count=7 -cpu=1 compared with main:

Query main this PR Allocations
No CTE 656 ns/op 655 ns/op 6 -> 6
Plain CTE 569 ns/op 611 ns/op 6 -> 6
Materialized CTE 805 ns/op 884 ns/op 6 -> 6
Not materialized CTE 708 ns/op 758 ns/op 6 -> 6
Nested CTE 957 ns/op 1,060 ns/op 7 -> 7

The corrected CTE path takes 7–11% longer than the baseline, which discards CTE syntax. The allocation profile attributes no heap allocations to the CTE tracker for these cases. A five-deep CTE exceeds the inline frame capacity and uses one extra allocation.

Compatibility

Affected CTE normalization output changes when alias retention is disabled. Consumers that derive query signatures from normalized SQL may see new signatures for those queries.

@joelmarcotte
joelmarcotte requested a review from a team as a code owner September 30, 2026 16:44
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