Skip to content

Translate captured IQueryable variables to common table expressions - #39803

Open
Aykuttonpc wants to merge 1 commit into
dotnet:mainfrom
Aykuttonpc:cte-embedded-queries
Open

Aykuttonpc wants to merge 1 commit into
dotnet:mainfrom
Aykuttonpc:cte-embedded-queries

Conversation

@Aykuttonpc

Copy link
Copy Markdown
Contributor

Fixes #29918

A captured IQueryable variable used inside a lambda of another query is now translated to a common table expression named after the variable, as agreed on #26486 (always translate to a CTE).

var lateOrders = context.Orders.Where(o => o.OrderDate > cutoff);
var customers = context.Customers
    .Where(c => lateOrders.Any(o => o.CustomerID == c.CustomerID) && lateOrders.Count() > 10);
WITH [lateOrders] AS (
    SELECT [o].[OrderID], [o].[CustomerID]
    FROM [Orders] AS [o]
    WHERE [o].[OrderDate] > @cutoff
)
SELECT ...
FROM [Customers] AS [c]
WHERE EXISTS (SELECT 1 FROM [lateOrders] AS [l] WHERE [l].[CustomerID] = [c].[CustomerID])
    AND (SELECT COUNT(*) FROM [lateOrders] AS [l0]) > 10

How it works

  • ExpressionTreeFuncletizer wraps the inlined query in EmbeddedQueryable.Marker(source, name). It's a plain method call, so every visitor visits the embedded query without knowing about the marker.
  • Core's TranslateEmbeddedQuery just returns the translated source, so non-relational providers behave as before. The relational override pushes it into a subquery carrying the CTE name. A relational provider without CTE support can override it the same way.
  • QuerySqlGenerator hoists all CTEs to the root statement (SELECT, UPDATE, DELETE), dedupes references to the same definition, and renames a CTE whose name clashes with a table, table alias, table-valued function or identifier in raw SQL.
  • SqlTreePruner removes CTE columns no reference uses.
  • SQL Server emits SET NOCOUNT OFF before WITH. SQLite's subquery-to-join rewriter and APPLY flattening leave CTE references alone.

Not translated to a CTE (inlined as before)

  • A bare DbSet assigned to an IQueryable variable.
  • Embedded queries whose projection can't be kept as a row source: entities nested in an anonymous type or DTO, subquery or collection projections, groupings, owned types.
  • A query passed directly to a top-level operator, e.g. .Union(lateOrders) or .Join(lateOrders, ...): Queryable splices in lateOrders.Expression, so there is no captured variable left.

References that need different columns (e.g. owned columns bound on one use only) become separate CTEs.

When a query references a captured IQueryable variable inside a lambda,
translate it to a named common table expression (WITH clause) instead of
inlining the subquery at every use site.

- The funcletizer wraps the captured query in an EmbeddedQueryable marker
  carrying the variable name. Non-relational providers translate it as
  before, since the default TranslateEmbeddedQuery inlines it; the
  relational override pushes it down into a subquery annotated with the
  CTE name.
- Navigation expansion keeps the embedded query's structure so the outer
  query can still bind navigations. Shapes that a snapshot can't keep
  (entities nested in an anonymous type or DTO, subquery or collection
  projections, groupings, owned types) stay inlined.
- QuerySqlGenerator hoists all CTEs to the root statement (SELECT, UPDATE,
  DELETE), dedupes them, and renames a CTE whose name clashes with a table,
  table alias, table-valued function or identifier in raw SQL.
- SqlTreePruner removes CTE columns that no reference uses.
- SQL Server emits SET NOCOUNT OFF before the WITH clause.
- SQLite's subquery-to-join rewriter and APPLY flattening leave CTE
  references alone, since the CTE is referenced by name.
- Join pruning doesn't treat a CTE-backed inner as the full table.

Fixes dotnet#29918

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Generated CTE names can exceed SQL Server’s identifier limit, while deduplicating volatile captured queries can change SQLite results by sharing a sample instead of evaluating references independently.

2 open issues
What changed in this PR

This PR translates eligible captured IQueryable variables into named common table expressions (CTEs), improving generated SQL readability and reuse as requested in #29918.

Changes:

  • Adds captured-query markers and translation hooks, retaining inline behavior for unsupported shapes.
  • Adds CTE generation, deduplication, name-collision handling, and shared-column pruning.
  • Adds relational regression tests and updates SQL Server and SQLite baselines.
File Description
test/​EFCore.SqlServer.FunctionalTests/​Query/​TemporalOwnedQuerySqlServerTest.cs Adds temporal owned-navigation baselines.
test/​EFCore.SqlServer.FunctionalTests/​Query/​TemporalGearsOfWarQuerySqlServerTest.cs Updates temporal query reuse baseline.
test/​EFCore.SqlServer.FunctionalTests/​Query/​SqlQuerySqlServerTest.cs Updates raw SQL composition baseline.
test/​EFCore.SqlServer.FunctionalTests/​Query/​OwnedQuerySqlServerTest.cs Adds owned-navigation and fallback baselines.
test/​EFCore.SqlServer.FunctionalTests/​Query/​NorthwindWhereQuerySqlServerTest.cs Updates captured-query predicate baselines.
test/​EFCore.SqlServer.FunctionalTests/​Query/​NorthwindCommonTableQuerySqlServerTest.cs Adds SQL Server CTE baselines.
test/​EFCore.SqlServer.FunctionalTests/​Query/​Inheritance/​TPTGearsOfWarQuerySqlServerTest.cs Updates table-per-type query reuse baseline.
test/​EFCore.SqlServer.FunctionalTests/​Query/​Inheritance/​TPCGearsOfWarQuerySqlServerTest.cs Updates table-per-concrete-type query reuse baseline.
test/​EFCore.SqlServer.FunctionalTests/​Query/​GearsOfWarQuerySqlServerTest.cs Updates shared-query parameter baseline.
test/​EFCore.SqlServer.FunctionalTests/​Query/​FromSqlQuerySqlServerTest.cs Updates captured FromSql baseline.
test/​EFCore.SqlServer.FunctionalTests/​Query/​AdHocMiscellaneousQuerySqlServerTest.cs Updates aggregate and nested-query baselines.
test/​EFCore.SqlServer.FunctionalTests/​BulkUpdates/​NorthwindBulkUpdatesSqlServerTest.cs Adds CTE update/delete baselines.
test/​EFCore.Sqlite.FunctionalTests/​Query/​NorthwindCommonTableQuerySqliteTest.cs Adds SQLite CTE baselines.
test/​EFCore.Sqlite.FunctionalTests/​Query/​GearsOfWarQuerySqliteTest.cs Updates shared-query parameter baseline.
test/​EFCore.Sqlite.FunctionalTests/​BulkUpdates/​NorthwindBulkUpdatesSqliteTest.cs Adds CTE update/delete baselines.
test/​EFCore.Relational.Specification.Tests/​Query/​OwnedQueryRelationalTestBase.cs Adds owned-navigation regression cases.
test/​EFCore.Relational.Specification.Tests/​Query/​NorthwindCommonTableQueryRelationalTestBase.cs Defines shared CTE and fallback tests.
test/​EFCore.Relational.Specification.Tests/​BulkUpdates/​NorthwindBulkUpdatesRelationalTestBase.cs Adds captured-query bulk operation tests.
src/​EFCore/​Query/​QueryableMethodTranslatingExpressionVisitor.cs Adds the provider translation hook.
src/​EFCore/​Query/​Internal/​NavigationExpandingExpressionVisitor.cs Handles markers and structural fallbacks.
src/​EFCore/​Query/​Internal/​ExpressionTreeFuncletizer.cs Names and marks captured queries.
src/​EFCore/​Query/​Internal/​EmbeddedQueryable.cs Defines the query marker method.
src/​EFCore/​EFCore.baseline.json Records the new translation API.
src/​EFCore.SqlServer/​Query/​Internal/​SqlServerQuerySqlGenerator.cs Handles CTE columns and statement ordering.
src/​EFCore.Sqlite.Core/​Query/​Internal/​SqliteSubqueryToJoinRewriter.cs Preserves named CTE references.
src/​EFCore.Sqlite.Core/​Query/​Internal/​SqliteApplyFlatteningExpressionVisitor.cs Prevents flattening CTE references.
src/​EFCore.Relational/​Query/​SqlTreePruner.cs Coordinates pruning across CTE references.
src/​EFCore.Relational/​Query/​SqlExpressions/​SelectExpression.cs Stores CTE names and supports pushdown.
src/​EFCore.Relational/​Query/​RelationalQueryableMethodTranslatingExpressionVisitor.cs Creates CTE sources and guards join pruning.
src/​EFCore.Relational/​Query/​QuerySqlGenerator.cs Hoists, deduplicates, names, and emits CTEs.
src/​EFCore.Relational/​EFCore.Relational.baseline.json Records relational CTE APIs.

Review effort: Balanced

Comment on lines +121 to +125
var existing = definitions.FindIndex(
d => string.Equals(d.OriginalName, name, StringComparison.Ordinal) && d.Normalized.Equals(normalized));
if (existing >= 0)
{
_commonTableNames[select] = definitions[existing].Name;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is intended: a captured variable names one set, so both references read the same rows, which is also what SQLite and PostgreSQL do for a CTE referenced more than once. Inlining volatile queries would add a fair amount of logic for a rare case, so I'd leave it unless you think otherwise.

continue;
}

var uniqueName = Uniquifier.Uniquify(name, usedNames, maxLength: int.MaxValue);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed this is possible in theory, but it needs a variable name over 128 characters. Plumbing the identifier limit into the SQL generator didn't seem worth it for that; happy to add it if you'd prefer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Translate embedded IQueryables to common table expressions (CTEs)

2 participants