Skip to content

Translate parameterized collection Contains to a native array parameter (#39) - #49

Merged
alex-clickhouse merged 8 commits into
mainfrom
feature/issue-39-array-contains-param
Nov 28, 2026
Merged

alex-clickhouse merged 8 commits into
mainfrom
feature/issue-39-array-contains-param

Conversation

@alex-clickhouse

@alex-clickhouse alex-clickhouse commented Jul 7, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #39.

What

A Contains over a captured collection sends the whole collection as one ClickHouse array parameter:

WHERE `p`.`id` IN ({ids1:Int64}, {ids2:Int64}, ..., {idsN:Int64})   -- EF Core expansion
WHERE `p`.`id` IN {ids:Array(Int64)}                                -- this PR

Why

With one parameter for each element, ClickHouse refuses the request when it has more than http_max_fields fields (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,000 Int64 values 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,000 Int64 values 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.VisitIn keeps the InExpression with its values parameter and applies an Array(T) mapping, with the store type of the tested column as element type (Array(Int64), Array(FixedString(3)), Array(UUID), ...). ClickHouseQuerySqlGenerator.GenerateIn writes it as item IN {p:Array(T)} or item NOT IN {p:Array(T)}.
  • ClickHouseArrayParameterTypeMapping changes the value when it binds the parameter: a null collection becomes an empty array, any IEnumerable<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.
  • The provider keeps the EF Core expansion for:
    • a tested item that can be null, or that has a Nullable store 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 an Array(Nullable(T)) column in an array lambda;
    • an element type with a value converter, for example an enum stored as Enum8;
    • element types that the driver does not format correctly inside an array. The supported types are the integers, floating point, decimal, bool, string, Guid, DateTime, DateOnly, BigInteger and IPAddress. TimeSpan is not supported, because the driver does not quote these elements;
    • EF.Constant(...) and EF.MultipleParameters(...);
    • all queries when the application sets UseParameterizedCollectionMode(Constant) or UseParameterizedCollectionMode(MultipleParameters). EF Core returns MultipleParameters also when nothing is set, so ClickHouseOptionsExtension records the mode that the application sets. The processor factory is a singleton, so the mode goes through IClickHouseSingletonOptions, as the SQL Server provider does with its compatibility level. UseParameterizedCollectionMode(Parameter) asks for one parameter, so Contains uses the array parameter with it.
  • ClickHouseQuerySqlGenerator.VisitSqlParameter registers the parameter value under its InvariantName and uses the Name in the SQL, as the base QuerySqlGenerator does. EF Core gives a parameter that a query uses with two type mappings a second Name (vals0) with the same InvariantName. The generator used the Name for both, 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 query with a scalar (e.Str == v || e.LcStr == v) fails on main too.
  • A collection used as a table (a join, ids.Where(...).Contains(...)) keeps the SELECT ... UNION ALL ... translation. EF.Parameter(...) does not translate, here and on main: EF Core then needs a table translation of the parameter (TranslatePrimitiveCollection), which the provider does not have.

Why IN and not has()

The first version of this PR 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 with 20M rows:

  • primary key: has() reads 9,766 of 9,766 granules, IN reads 3;
  • 10,000 elements on a column without an index: has() did not finish in 60 s, IN took 0.29 s.

26.3 and 26.11 rewrite has() to IN, so CI (:latest) cannot show the difference.

Review comments

  • HashSet<T> and lazy sequences (thread 1): driver 1.5.0 formats any IEnumerable, and the new mapping reads the sequence one time. Tests cover HashSet<T>, a lazy Where/Select and ImmutableArray<T>.
  • Null elements (thread 2): confirmed. For int?[] { 5, null, 7 } the driver sends [5,,7], the server reads 0, and the query also returned rows with 0. A null string element threw NullReferenceException. A null collection failed with CANNOT_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 the default profile 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 add UseFormDataParameters=true to 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:

  • SQL shape and results for Int32, Int64, String, Guid, DateTime, DateOnly, BigInteger, IPAddress, decimal, bool, List<T>, HashSet<T>, a lazy sequence and ImmutableArray<T>;
  • a null element does not match the column default (0, ''), also when negated; a null collection matches no rows; a long[] against an Int32 column (EF Core casts the column);
  • the EF Core expansion for a nullable column, a Nullable store type after a null check, an enum, EF.Constant, EF.MultipleParameters, an inline collection, a join, and an explicit UseParameterizedCollectionMode(Constant) or (MultipleParameters); the array parameter with UseParameterizedCollectionMode(Parameter); a context without the mode still gets the array parameter; a different mode on a shared internal service provider throws;
  • one collection and one scalar against a String and a LowCardinality(String) column; a byte[] against a UInt8 column (Array(UInt8), not binary text); the EF Core expansion for a nullable column and an enum with UseParameterizedCollectionMode(Parameter);
  • an empty collection, a negated Contains, Contains in 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.Tests 767 passed; EFCore.ClickHouse.FunctionalTests 323 passed, 4 skipped (the known NorthwindJoinQueryClickHouseTest skips). Build: 0 errors; warnings are the same as on main (359, compared by file and code).

Design notes

  • A future TranslatePrimitiveCollection (for example with arrayJoin) could make EF.Parameter(...) and joins over a captured collection use one array parameter too.
  • The explicit collection mode is the first value in 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 Contains filters (e.g. ids.Contains(x.Id)) now translate to column IN {ids:Array(T)} with one ClickHouse array parameter instead of EF Core’s per-element IN ({ids1}, {ids2}, …), avoiding ClickHouse’s ~1,000 http_max_fields limit and supporting much larger lists (bounded mainly by http_max_field_value_size).

ClickHouseSqlNullabilityProcessor picks the array path by default (or when UseParameterizedCollectionMode(Parameter) is set) and falls back to EF’s expansion for nullable columns, value converters (enums), unsupported element types, and explicit EF.Constant / EF.MultipleParameters or Constant / MultipleParameters modes. ClickHouseArrayParameterTypeMapping binds IEnumerable once, strips null elements, and treats a null collection as empty. ClickHouseQuerySqlGenerator emits array IN/NOT IN and fixes parameter lookup to use InvariantName when EF reuses one value under two SQL names (e.g. String vs LowCardinality(String)).

ClickHouseOptionsExtension tracks explicit collection mode for singleton options and service-provider hashing; ClickHouseParameterBasedSqlProcessorFactory now takes IClickHouseSingletonOptions. Docs and a large ParameterizedContainsTests integration 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.

…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

codecov Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

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>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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 InExpression with a collection ValuesParameter into has({p:Array(T)}, item) in ClickHouseSqlNullabilityProcessor, 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.Driver to 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.

@DanielBunting DanielBunting 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.

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.

alex-clickhouse and others added 5 commits November 27, 2026 14:17
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>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.

Fix All in Cursor

❌ 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.

@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

AI review gate — AI review passed

Clean 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>

@security-ai-gate-reviewer security-ai-gate-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Auto-approved by the AI review gate on 05a39a9. Details in the approver's comment on this pull request.

@security-ai-gate-reviewer

Copy link
Copy Markdown

AI review gate — auto-approved

05a39a94231e is approved by security-ai-gate-reviewer[bot], an automated identity, not a human. The approval stands on the required AI review: Cursor Bugbot concluded green on this commit and the AI review gate is SUCCESS (its own comment has the verdict), and the change touches no path that requires a human reviewer. It is bound to this commit: a new push dismisses it and the approver re-evaluates.

History (latest 5 heads, newest first)

  • 05a39a94231e approved — green: Cursor Bugbot

@alex-clickhouse
alex-clickhouse merged commit d16e5db into main Nov 28, 2026
6 checks passed
alex-clickhouse added a commit that referenced this pull request Nov 28, 2026
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>
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.

Translate parameterized collection Contains to a native ClickHouse array parameter

3 participants