Add support for Data Modifying Common Table Expressions (CTEs) in PostgreSQL backend - #821
Merged
Merged
Conversation
- Introduced `pgWithSyntax` to prefix PostgreSQL statements with CTEs. - Added new types for data-modifying CTEs: `PgDataModifyingCommonTableExpressionSyntax` and `PgCommonTableExpressionSyntax`. - Implemented type classes for handling CTEs in SQL queries, ensuring correct placement of data-modifying CTEs. - Created unit and integration tests for rendering and type safety of CTEs, including negative tests for invalid placements. - Updated documentation to reflect new CTE capabilities and usage examples. - Modified test setup to use PostgreSQL version 18.4 for better compatibility.
kushagarr
marked this pull request as ready for review
July 11, 2026 08:42
LaurentRDC
reviewed
Jul 13, 2026
- Updated CTE handling in tests to reflect PostgreSQL's behavior with zero-column CTEs and side-effect-only CTEs. - Added new tests for materialization execution and rendering, ensuring compliance with PostgreSQL 12+ features. - Refined error handling for invalid CTE placements, particularly for side-effect-only operations. - Improved documentation on PostgreSQL-specific CTE usage, including materialization options and nested CTEs. - Adjusted dependencies in the SQLite library for compatibility. - Ensured reproducibility of CI runs by pinning PostgreSQL server version.
LaurentRDC
reviewed
Jul 15, 2026
LaurentRDC
reviewed
Jul 16, 2026
Member
|
We're getting really close! |
Contributor
Author
|
It closes #290 |
LaurentRDC
approved these changes
Jul 16, 2026
LaurentRDC
left a comment
Member
There was a problem hiding this comment.
Awesome, thanks @kushagarr!
Member
|
@kushagarr released in beam-postgres 0.6.3.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR adds PostgreSQL-specific support for data-modifying and explicitly
materialized common table expressions in
beam-postgres, without changingthe portable CTE API or SQL99 abstractions in
beam-core.The implementation introduces a placement-indexed
PgWithbuilder whichcaptures PostgreSQL’s rule that data-modifying CTEs must be attached to a
top-level statement. It supports
WITHstatements terminating inSELECT,INSERT,UPDATE, orDELETE, while preserving compatibility with existingportable
With Postgreshelpers.A complete
WITH ... <terminal statement>is represented as one Beamstatement and sent to PostgreSQL in one database round trip.
PostgreSQL-specific builder
PgWithis indexed byPgCtePlacement:PgCteNestedAllowedrepresents SELECT-only CTE blocks which may be embeddedin a subquery.
PgCteTopLevelOnlyrepresents blocks containing data-modifying CTEs.pgSelectWithNestedaccepts only nested-safe blocks.pgSelectWithTopLevel,pgInsertWith,pgUpdateWith, andpgDeleteWithproduce top-level statements and therefore accept either placement.
The placement parameter has a nominal role, preventing
Data.Coercefromrelabelling a top-level-only block as nested-safe.
Existing helpers built with
With Postgrescan be composed usingpgLiftWith.Lifted and PostgreSQL-specific CTEs use the same name supply, so their generated
CTE names cannot collide.
Recursive construction is restricted to SELECT-only blocks.
pgToTopLevelallows a completed recursive SELECT block to feed a later data-modifying CTE
without permitting a modifying CTE to refer recursively to itself.
Supported CTEs
SELECT CTEs can be introduced with:
pgSelectingpgSelectingWith PgCteDefaultpgSelectingWith PgCteMaterializedpgSelectingWith PgCteNotMaterializedExplicit
MATERIALIZEDandNOT MATERIALIZEDmodifiers require PostgreSQL 12or later.
PgCteDefaultemits no modifier and retains PostgreSQL’s normalplanner behaviour and compatibility with older server versions.
Reusable data-modifying CTEs are provided by:
cteInsertReturningcteUpdateReturningcteDeleteReturningTheir
RETURNINGoutput is exposed throughReusableQand can be consumed bylater CTEs or the terminal statement using
reuse.Side-effect-only variants are also provided:
cteInsertcteUpdatecteDeleteThese omit
RETURNING, return(), and still execute when the surroundingtop-level statement runs.
Zero-column projections
Reusable CTE projections containing no fields are supported.
For a zero-column SELECT CTE, Beam omits PostgreSQL’s optional CTE column-alias
list. This preserves the query’s row cardinality without exposing any result
fields.
PostgreSQL requires a data-modifying
RETURNINGclause to contain at least oneexpression. For a zero-field
cteInsertReturning,cteUpdateReturning, orcteDeleteReturningprojection, Beam therefore emits a privateNULL::booleansentinel:The sentinel is not exposed to Beam’s result decoder. It preserves one
zero-field result row for every affected row, allowing the reusable result to
participate in
COUNT(*),EXISTS, joins, and repeated reuse.When no later CTE or terminal statement needs the affected rows, the
side-effect-only builders should be used instead; they omit
RETURNINGentirely.
Terminal statements and no-op handling
A
PgWithblock may terminate with:pgSelectWithTopLevelpgInsertWithpgUpdateWithpgDeleteWithThe DML consumers retain Beam’s existing
SqlInsert,SqlUpdate, andSqlDeletewrappers, so the existing PostgreSQLreturningAPI remainsavailable for the terminal statement.
Empty inserts and identity updates remain Beam no-ops. Since PostgreSQL cannot
execute a bare
WITHblock, accumulated CTE definitions are discarded whenthere is no terminal statement.
This PR also fixes
pgSelectWithwith an empty CTE block: it now renders theunderlying SELECT directly instead of producing an invalid empty
WITHclause.
Documentation
The Haddock documentation and PostgreSQL user guide include paired Beam and
generated-SQL examples covering:
The Chinook documentation fixture is pinned to the revision matching its
verified checksum, making clean documentation builds reproducible.
Testing
The test suite covers:
MATERIALIZEDandNOT MATERIALIZEDCOUNT(*),EXISTS, joins, and repeated reuseand reuse of side-effect-only CTE results