Repository navigation
Translate parameterized collection Contains to a native array parameter (#39) - #49
Conversation
…er (#39) A captured collection used with Contains (ids.Contains(x.Id)) now binds as a single native Array(T) parameter — has({ids:Array(T)}, column) — instead of EF Core's default one-scalar-parameter-per-element IN(...) expansion. This removes the parameter-count / query-size ceilings that large IN lists hit and keeps the query text and plan-cache key independent of the collection size. Implemented in ClickHouseSqlNullabilityProcessor.VisitIn: an InExpression with a collection ValuesParameter is rewritten to has() when the parameter is unmarked (provider default) or explicitly EF.Parameter. The array element store type is aligned to the tested column's mapping. Per-query markers are honored — EF.MultipleParameters keeps the per-element expansion and EF.Constant inlines the values. Element types requiring a value conversion (e.g. CLR enum -> Enum8) and collections used as a queryable source (joins, Where(...).Contains(...)) fall back to the existing expansion / SELECT ... UNION ALL ... path. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Bumps ClickHouse.Driver 1.1.0 → 1.3.0 (full unit + functional suites green on 1.3.0). 1.3.0 quotes temporal elements inside array parameters correctly, so the parameterized-Contains array path (#39) can now cover more types. Expanded ArrayParameterElementTypes, verified empirically against 1.3.0, to add DateTime/DateTime64, Date/Date32 (DateOnly), Int128/Int256/UInt128/UInt256 (BigInteger), and IPv4/IPv6 (IPAddress). TimeSpan/Time stays excluded — the driver still serializes its array elements unquoted (CANNOT_READ_ARRAY). Added integration tests for the new element types. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
Pull request overview
This PR enhances the ClickHouse EF Core provider’s translation of Contains over captured/parameterized primitive collections by binding the collection as a single native Array(T) parameter and rewriting the predicate to has(arrayParam, column), avoiding large IN (p1, …, pN) expansions and parameter-count/query-size limits. It also bumps ClickHouse.Driver to 1.3.0 and updates docs/tests accordingly.
Changes:
- Rewrite
InExpressionwith a collectionValuesParameterintohas({p:Array(T)}, item)inClickHouseSqlNullabilityProcessor, with guarded fallbacks for cases where semantics/serialization could differ. - Add a new integration test suite (
ParameterizedContainsTests) and update existing tests to assert the new SQL shape. - Update documentation (README/CHANGELOG/RELEASENOTES) and bump
ClickHouse.Driverto 1.3.0 across provider and test projects.
Reviewed changes
Copilot reviewed 10 out of 10 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
| test/EFCore.ClickHouse.Tests/ParameterizedContainsTests.cs | New integration coverage for array-parameter Contains translation across types and fallback cases. |
| test/EFCore.ClickHouse.Tests/ExtendedTypeMappingTests.cs | Updates an existing test to assert the new captured-collection array-parameter behavior. |
| test/EFCore.ClickHouse.Tests/EFCore.ClickHouse.Tests.csproj | Bumps ClickHouse.Driver dependency to 1.3.0 for the test project. |
| test/EFCore.ClickHouse.Tests/ClickHouseQuerySqlGeneratorTests.cs | Updates SQL-shape assertion to expect array-parameter Contains translation for captured collections. |
| test/EFCore.ClickHouse.FunctionalTests/EFCore.ClickHouse.FunctionalTests.csproj | Bumps ClickHouse.Driver dependency to 1.3.0 for functional tests. |
| src/EFCore.ClickHouse/Query/Internal/ClickHouseSqlNullabilityProcessor.cs | Implements the IN {collectionParameter} → has(arrayParam, item) rewrite with type-mapping alignment and guarded fallbacks. |
| src/EFCore.ClickHouse/EFCore.ClickHouse.csproj | Bumps provider dependency on ClickHouse.Driver to 1.3.0. |
| RELEASENOTES.md | Documents the new Contains behavior and driver bump for the next release. |
| README.md | Adds user-facing documentation for the new captured-collection Contains translation and opt-outs. |
| CHANGELOG.md | Records the feature and dependency bump with detailed behavior notes and limitations. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
I'd probably look to bolt onto IEnumerable<T> rather than T[] as it currently breaks paths that worked prior.
You could achieve this by extending ClickHouseArrayTypeMapping specifically for array parameters (dropping null values and rolling out any lazy enumerables). I've created the changes that may get you a little closer here: https://github.com/DanielBunting/ClickHouse.EntityFrameworkCore/tree/pr-49-review
Note: I think your driver bump may have fixed the HashSet/Lazy cases, but it would still be worth checking with null values in the collection as this could be a silent breakage - an int?[] [1, null, 3] will resolve to [1, 0, 3] and this feels off.
Conflicts: the three csproj files, where this branch pinned ClickHouse.Driver 1.3.0 and main has 1.5.0 (main kept), and the changelogs and README, where both sides added entries (both kept; the Contains entry moves under "Query translation", and the 1.3.0 dependency entry goes because main already documents 1.5.0). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ments
The provider wrote `has({ids:Array(T)}, column)`. ClickHouse before 26.3
does not use the primary key for has() and compares each row with each
element: on 25.8, a 10,000-element list over 20M rows did not finish in
60 s, where `column IN {ids:Array(T)}` takes 0.3 s and reads only the
matching granules. The processor now keeps the InExpression with its
values parameter, and ClickHouseQuerySqlGenerator writes it as
`item IN {p:Array(T)}` (or `NOT IN`).
The driver cannot send a null element in an Array(T) of a type that is
not Nullable: it sends `[5,,7]`, which the server reads as [5, 0, 7], so
`int?[] { 5, null, 7 }` matched rows with 0, and a null string element
threw NullReferenceException. A null collection failed on the server
(CANNOT_READ_ARRAY_FROM_TEXT). ClickHouseArrayParameterTypeMapping now
changes the value when it binds the parameter: a null collection becomes
an empty array, any sequence is read one time, and null elements are
removed. Removing them is correct because the provider uses the array
parameter only for an item that is never null. Binding is the only step
that sees the values and lets EF Core cache the SQL, so the processor
does not read them.
The approach of a parameter mapping that removes nulls comes from
Daniel Bunting's review.
Co-Authored-By: Daniel Bunting <10263673+DanielBunting@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`UseParameterizedCollectionMode(Constant)` or `(MultipleParameters)` had no effect on `Contains`, because EF Core reports MultipleParameters both when the application sets it and when it sets nothing. ClickHouseOptionsExtension now records the mode that the application sets, and the nullability processor uses the EF Core expansion for every collection when there is such a mode. Per-query EF.Constant and EF.MultipleParameters work as before. The processor factory is a singleton, so the mode goes through IClickHouseSingletonOptions, as the SQL Server provider does with its compatibility level. A context with a different mode gets a different internal service provider. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The entries named has(), said that EF.Parameter selects the array parameter, and said that the array parameter removes the size limit. They now give the IN translation, the two server limits with their defaults (http_max_fields for one parameter per element, http_max_field_value_size for one array), how to raise the second one (server profile and restart; a request setting has no effect), and the model-wide collection mode. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- ClickHouseQuerySqlGenerator: EF Core gives a parameter that a query uses with two type mappings a second Name (`vals0`) with the same InvariantName. The generator registered the parameter with the Name as invariant name, so `vals.Contains(e.Str) || vals.Contains(e.LcStr)` (String and LowCardinality(String)) failed with "No value was provided for the required parameter 'vals0'". The same happened for a scalar (`e.Str == v || e.LcStr == v`) on main. The generator now registers the InvariantName for the value and the Name for the SQL, and keeps a set of names, as the base QuerySqlGenerator does. - With UseParameterizedCollectionMode(Parameter) for all queries, EF Core still builds an IN with a values parameter for Contains, and the processor used the EF Core expansion. That mode asks for one parameter, so the processor now uses the array parameter for it. - The processor reports the parameter of an array lambda as never null, also for an Array(Nullable(T)) column, so the array path removed null elements that can match. The processor now uses the EF Core expansion also when the store type of the item is Nullable. - Docs: the 128 KiB limit counts URL-encoded text (about 5,900 Int64 values of 19 digits, 2,900 GUIDs); raising it also needs UseFormDataParameters=true because of http_max_uri_size; the Parameter mode; the new constructor parameter of the processor factory; DateTimeOffset removed from the list of unsupported types. - Tests for each item, for Contains in a projection, and for the Validate check of the singleton options. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 9bf4313. Configure here.
AI review gate — AI review passedClean review from: Cursor Bugbot. |
With UseParameterizedCollectionMode(Parameter), a nullable column and an enum still get the EF Core expansion with one parameter for each element: SqlNullabilityProcessor expands the Parameter mode in the same way as MultipleParameters. A byte[] collection against a UInt8 column binds as Array(UInt8): the driver formats a byte[] as binary text only for String and FixedString. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Auto-approved by the AI review gate on 05a39a9. Details in the approver's comment on this pull request.
AI review gate — auto-approved
History (latest 5 heads, newest first)
|
The automatic rebase onto main after #49 merged moved the branch, but the pull request did not get the new head. This commit has no changes. It makes a normal push, so GitHub updates the pull request and runs the checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Closes #39.
What
A
Containsover a captured collection sends the whole collection as one ClickHouse array parameter:Why
With one parameter for each element, ClickHouse refuses the request when it has more than
http_max_fieldsfields (1,000 by default):HTML Form Exception: Too many form fields. Measured on 26.11 with the EF Core expansion: 2,000 GUIDs and 5,000Int64values fail. With one array parameter, the limit is the size of one parameter value,http_max_field_value_size(128 KiB by default). The driver sends parameters URL-encoded in the URL, so a comma counts as 3 bytes: about 10,000Int64values of 10 digits, 5,900 of 19 digits, or 2,900 GUIDs. The SQL text also does not depend on the size of the collection.How
ClickHouseSqlNullabilityProcessor.VisitInkeeps theInExpressionwith its values parameter and applies anArray(T)mapping, with the store type of the tested column as element type (Array(Int64),Array(FixedString(3)),Array(UUID), ...).ClickHouseQuerySqlGenerator.GenerateInwrites it asitem IN {p:Array(T)}oritem NOT IN {p:Array(T)}.ClickHouseArrayParameterTypeMappingchanges the value when it binds the parameter: a null collection becomes an empty array, anyIEnumerable<T>is read one time, and null elements are removed. Removing them is correct because the provider uses this path only when the tested item is never null. Binding is the only step that sees the values without stopping EF Core from caching the SQL, so the processor does not read them.Nullablestore type (the expansion adds the null checks for .NET semantics). The store type check is for items that the nullability processor reports as never null although they can be NULL, for example the element of anArray(Nullable(T))column in an array lambda;Enum8;decimal,bool,string,Guid,DateTime,DateOnly,BigIntegerandIPAddress.TimeSpanis not supported, because the driver does not quote these elements;EF.Constant(...)andEF.MultipleParameters(...);UseParameterizedCollectionMode(Constant)orUseParameterizedCollectionMode(MultipleParameters). EF Core returnsMultipleParametersalso when nothing is set, soClickHouseOptionsExtensionrecords the mode that the application sets. The processor factory is a singleton, so the mode goes throughIClickHouseSingletonOptions, as the SQL Server provider does with its compatibility level.UseParameterizedCollectionMode(Parameter)asks for one parameter, soContainsuses the array parameter with it.ClickHouseQuerySqlGenerator.VisitSqlParameterregisters the parameter value under itsInvariantNameand uses theNamein the SQL, as the baseQuerySqlGeneratordoes. EF Core gives a parameter that a query uses with two type mappings a secondName(vals0) with the sameInvariantName. The generator used theNamefor both, sovals.Contains(e.Str) || vals.Contains(e.LcStr)(StringandLowCardinality(String)) failed withNo value was provided for the required parameter 'vals0'. The same query with a scalar (e.Str == v || e.LcStr == v) fails onmaintoo.ids.Where(...).Contains(...)) keeps theSELECT ... UNION ALL ...translation.EF.Parameter(...)does not translate, here and onmain: EF Core then needs a table translation of the parameter (TranslatePrimitiveCollection), which the provider does not have.Why
INand nothas()The first version of this PR wrote
has({ids:Array(T)}, column). ClickHouse before 26.3 does not use the primary key forhas()and compares each row with each element. On 25.8 with 20M rows:has()reads 9,766 of 9,766 granules,INreads 3;has()did not finish in 60 s,INtook 0.29 s.26.3 and 26.11 rewrite
has()toIN, so CI (:latest) cannot show the difference.Review comments
HashSet<T>and lazy sequences (thread 1): driver 1.5.0 formats anyIEnumerable, and the new mapping reads the sequence one time. Tests coverHashSet<T>, a lazyWhere/SelectandImmutableArray<T>.int?[] { 5, null, 7 }the driver sends[5,,7], the server reads0, and the query also returned rows with0. A null string element threwNullReferenceException. A null collection failed withCANNOT_READ_ARRAY_FROM_TEXT. The mapping in the second bullet of "How" fixes all three, as Daniel suggested in his review.Limits
To raise
http_max_field_value_size, set it in thedefaultprofile of the server configuration and restart the server. A value in the URL or the connection string has no effect (measured on 26.11). Also addUseFormDataParameters=trueto the connection string, so that the driver sends the parameters in the request body: in the URL,http_max_uri_size(1 MiB by default) also applies.Tests
ParameterizedContainsTests, against a real ClickHouse through Testcontainers:Int32,Int64,String,Guid,DateTime,DateOnly,BigInteger,IPAddress,decimal,bool,List<T>,HashSet<T>, a lazy sequence andImmutableArray<T>;0,''), also when negated; a null collection matches no rows; along[]against anInt32column (EF Core casts the column);Nullablestore type after a null check, an enum,EF.Constant,EF.MultipleParameters, an inline collection, a join, and an explicitUseParameterizedCollectionMode(Constant)or(MultipleParameters); the array parameter withUseParameterizedCollectionMode(Parameter); a context without the mode still gets the array parameter; a different mode on a shared internal service provider throws;Stringand aLowCardinality(String)column; abyte[]against aUInt8column (Array(UInt8), not binary text); the EF Core expansion for a nullable column and an enum withUseParameterizedCollectionMode(Parameter);Contains,Containsin a projection, and 12,000 values in one parameter.Each new test for a fix fails when the fix is reverted.
Full suites:
EFCore.ClickHouse.Tests767 passed;EFCore.ClickHouse.FunctionalTests323 passed, 4 skipped (the knownNorthwindJoinQueryClickHouseTestskips). Build: 0 errors; warnings are the same as onmain(359, compared by file and code).Design notes
TranslatePrimitiveCollection(for example witharrayJoin) could makeEF.Parameter(...)and joins over a captured collection use one array parameter too.IClickHouseSingletonOptions. A context with a different mode gets a different internal service provider.🤖 Generated with Claude Code
Note
Medium Risk
Changes default SQL and parameter binding for a common LINQ pattern; fallbacks preserve prior behavior for nullable/enums/opt-in modes, with broad integration coverage.
Overview
Captured
Containsfilters (e.g.ids.Contains(x.Id)) now translate tocolumn IN {ids:Array(T)}with one ClickHouse array parameter instead of EF Core’s per-elementIN ({ids1}, {ids2}, …), avoiding ClickHouse’s ~1,000http_max_fieldslimit and supporting much larger lists (bounded mainly byhttp_max_field_value_size).ClickHouseSqlNullabilityProcessorpicks the array path by default (or whenUseParameterizedCollectionMode(Parameter)is set) and falls back to EF’s expansion for nullable columns, value converters (enums), unsupported element types, and explicitEF.Constant/EF.MultipleParametersorConstant/MultipleParametersmodes.ClickHouseArrayParameterTypeMappingbindsIEnumerableonce, strips null elements, and treats a null collection as empty.ClickHouseQuerySqlGeneratoremits arrayIN/NOT INand fixes parameter lookup to useInvariantNamewhen EF reuses one value under two SQL names (e.g.StringvsLowCardinality(String)).ClickHouseOptionsExtensiontracks explicit collection mode for singleton options and service-provider hashing;ClickHouseParameterBasedSqlProcessorFactorynow takesIClickHouseSingletonOptions. Docs and a largeParameterizedContainsTestsintegration suite cover types, edge cases, and opt-outs.Reviewed by Cursor Bugbot for commit 05a39a9. Bugbot is set up for automated code reviews on this repo. Configure here.