Skip to content
Merged
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ v0.3.1 (Unreleased)
* `ClickHouseMigrationsSqlGenerator` and `ClickHouseDatabaseCreator` take `IDbContextOptions` (and the creator also `IRelationalTypeMappingSource`) in their constructors. A subclass must pass them on.

### Query translation
* **`Contains` over a captured collection sends one `Array(T)` parameter.** `ids.Contains(x.Id)` translates to ``x.Id IN {ids:Array(Int64)}`` instead of the EF Core expansion with one parameter for each element (`IN ({ids1:Int64}, {ids2:Int64}, …)`). ClickHouse refuses a request with more than `http_max_fields` (1,000) fields, so the expansion failed for a list of about 1,000 values. The SQL text does not depend on the size of the collection, and ClickHouse uses the primary key for `IN` with an array. The element type is the store type of the tested column (`Array(Int64)`, `Array(FixedString(3))`, `Array(UUID)`, …). The collection can be any `IEnumerable<T>`: `ClickHouseArrayParameterTypeMapping` reads it one time when it binds the parameter, removes null elements, and sends a null collection as an empty array. The supported element types are the integers, floating point, `decimal`, `bool`, `string`, `Guid`, `DateTime`, `DateOnly`, `BigInteger` and `IPAddress`. The provider keeps the EF Core expansion for a tested item that can be null or has a `Nullable` store type (the expansion adds the null checks), for an element with a value converter (for example an enum stored as `Enum8`), for other element types (for example `TimeSpan`, which the driver does not quote inside an array), for `EF.Constant(…)` and `EF.MultipleParameters(…)`, and for all queries when `UseParameterizedCollectionMode` is set to `Constant` or `MultipleParameters`. With `UseParameterizedCollectionMode(Parameter)`, `Contains` uses the array parameter. A collection used as a table (a join, `ids.Where(…).Contains(…)`) keeps the `SELECT … UNION ALL …` translation, and `EF.Parameter(…)` does not translate, because EF Core then needs a table translation of the parameter, which the provider does not have. One parameter value can have at most `http_max_field_value_size` bytes (128 KiB by default), and the driver sends parameters URL-encoded in the URL, so a comma counts as 3 bytes. That is about 10,000 `Int64` values of 10 digits, 5,900 of 19 digits, or 2,900 GUIDs. A longer list fails with `HTML Form Exception: Field value too long`. To raise the limit, set `http_max_field_value_size` in the `default` profile of the server configuration and restart the server; the setting has no effect in the connection string. Add `UseFormDataParameters=true` to the connection string too, so that the driver sends the parameters in the request body: in the URL, `http_max_uri_size` (1 MiB by default) also applies. `ClickHouseParameterBasedSqlProcessorFactory` takes `IClickHouseSingletonOptions` in its constructor; a subclass must pass it on. ([#39](https://github.com/ClickHouse/ClickHouse.EntityFrameworkCore/issues/39))
* **`toStartOf*` date-time functions** via `EF.Functions`: `ToStartOfYear`, `ToStartOfQuarter`, `ToStartOfMonth`, `ToStartOfWeek` (with optional week `mode`), `ToStartOfDay`, `ToStartOfHour`, `ToStartOfMinute`, `ToStartOfSecond`, the fixed buckets `ToStartOfFiveMinutes` / `ToStartOfTenMinutes` / `ToStartOfFifteenMinutes`, and the general `ToStartOfInterval(source, value, unit)`. Each maps to the matching ClickHouse function and works in `GROUP BY`. Return types follow ClickHouse: the calendar buckets (`Year`/`Quarter`/`Month`/`Week`) return `Date`, the day/hour/minute buckets return `DateTime`, and `ToStartOfSecond` returns `DateTime64`. All accept `DateTime`/`DateTime64` columns, and the plain truncation functions also accept `DateOnly`; `ToStartOfInterval` requires a `DateTime`/`DateTime64` column on older ClickHouse, which rejects a `DateOnly` (Date/Date32) source with `Illegal type Date32 of 1st argument` for every unit; recent versions accept it. `ToStartOfInterval` takes a `ClickHouseInterval` unit (`Second`…`Year`) and emits `toStartOfInterval(source, toInterval<unit>(value))`; the unit must be a constant so it can be translated. The default `Date`/`DateTime` result types only span 1970–2149/2106, so ClickHouse narrows out-of-range values — enable `enable_extended_results_for_datetime_functions` (e.g. `set_enable_extended_results_for_datetime_functions=1` in the connection string) for range-preserving `Date32`/`DateTime64` results.

### Bug fixes
* A query that compares one captured value with columns of two store types (for example `e.Name == name || e.Code == name`, with `String` and `LowCardinality(String)` columns) no longer fails with `No value was provided for the required parameter 'name0'`. EF Core gives the second use a new parameter name (`name0`) with the same invariant name, and `ClickHouseQuerySqlGenerator` used the new name to look up the value. It now uses the invariant name for the value and the new name in the SQL, as the base `QuerySqlGenerator` does.
* **Code-only driver settings on `UseClickHouse(DbConnection)` and `UseClickHouse(DbDataSource)`** are no longer lost. To add `join_use_nulls`, the provider rewrote the connection string of the connection on open, and it built the master connection for `EnsureCreated`, `EnsureDeleted` and migrations from the connection string. Both dropped every setting with no connection-string key, such as `SkipServerCertificateValidation`, `BearerToken`, `CustomHeaders`, `HttpClient` and `LoggerFactory`, so a server with a self-signed certificate failed with an untrusted-root error. The provider now sends `join_use_nulls=1` as a setting of each statement that it sends (EF Core commands, inserts and database creation) and does not change the connection, and the master connection is a clone of the connection that uses the same driver client with the `default` database. A context that uses a `ClickHouseDataSource` therefore keeps the data source client and its HTTP connection pool, where it got a new client and HTTP connection pool for each context. A `join_use_nulls` value in the connection settings still wins, and an EF Core interceptor that wraps the command in `CommandCreated` still gets the setting, because the provider adds it before application interceptors run. An interceptor that supplies its own command in `CommandCreating` does not. A connection of another type, for example a profiler wrapper around a `ClickHouseConnection`, still gets `set_join_use_nulls=1` in its connection string on open, which loses the code-only settings of the inner connection. **Behaviour change:** with these two overloads, a command that you create yourself on `Database.GetDbConnection()` does not get `join_use_nulls=1`. ([#50](https://github.com/ClickHouse/ClickHouse.EntityFrameworkCore/issues/50))
* Migration scripts (`dotnet ef migrations script`, `IMigrator.GenerateScript()`) end every statement with `;`. EF Core puts only a line break between the commands of a script, and the `ALTER TABLE`, `RENAME TABLE`, `CREATE DATABASE` and `DROP DATABASE` statements had no terminator, so `clickhouse-client` read two statements as one and failed with a syntax error. Migrations that run from code were not affected, because the provider sends each statement separately.
* `ToStartOfWeek` now rejects row-dependent week modes during query translation, and `ToStartOfInterval` likewise rejects row-dependent interval sizes. ClickHouse requires these operands to be constant for the query; literals and captured query parameters remain supported.
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ This provider is in active development. It supports **LINQ queries**, **inserts*

`Where`, `OrderBy`, `Take`, `Skip`, `Select`, `First`, `Single`, `Any`, `Count`, `Distinct`, `AsNoTracking`

`Contains` over a captured collection (`Where(x => ids.Contains(x.Id))`) sends the whole collection as one `Array(T)` parameter: ``x.Id IN {ids:Array(Int64)}``. With one parameter for each element, ClickHouse refuses a request with more than 1,000 fields (`http_max_fields`), so a list of about 1,000 values fails. The array has the store type of the column. Any `IEnumerable<T>` works, and a null collection matches no rows, as in EF Core. The provider sends one parameter for each element for a nullable column, for an element type with a value converter (for example an enum), and for element types that the driver does not format inside an array, such as `TimeSpan`. To get one parameter for each element, use `EF.MultipleParameters(ids)` for one query or `UseParameterizedCollectionMode(ParameterTranslationMode.MultipleParameters)` for all queries; `EF.Constant(ids)` writes the values into the SQL. One parameter value can have at most `http_max_field_value_size` bytes (128 KiB by default), and the driver sends parameters URL-encoded in the URL, so a comma counts as 3 bytes. That is about 10,000 `Int64` values of 10 digits, 5,900 of 19 digits, or 2,900 GUIDs. A longer list fails with `HTML Form Exception: Field value too long`. To raise the limit, set `http_max_field_value_size` in the `default` profile of the server configuration and restart the server; the setting has no effect in the connection string. Add `UseFormDataParameters=true` to the connection string too, so that the driver sends the parameters in the request body: in the URL, `http_max_uri_size` (1 MiB by default) also applies.

### Joins

`Join` (INNER JOIN), `GroupJoin` + `SelectMany` + `DefaultIfEmpty` (LEFT JOIN), `SelectMany` (CROSS JOIN), and self-joins. Joining a local sequence (`int[]`, `string[]`, `byte[]`) also works, as does `Contains` against a local collection (`T[]`, `List<T>`, and the `ICollection`/`IList`/`IReadOnlyList` interfaces), which becomes an `IN` predicate.
Expand Down
2 changes: 2 additions & 0 deletions RELEASENOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ v0.3.1 (Unreleased)
* **Replicated tables and clusters.** Call `.WithReplication()` on a MergeTree-family engine to get its Replicated variant, for example `HasReplacingMergeTreeEngine("Version").WithReplication()` creates a `ReplicatedReplacingMergeTree` table. ClickHouse then uses its default Keeper path and replica name; to set them yourself, use `.WithReplication("/clickhouse/tables/{shard}/{database}/{table}", "{replica}")`. To run the DDL on all hosts of a cluster, add `UseCluster("my_cluster")` to `UseClickHouse(...)`: migrations, `EnsureCreated()` and `EnsureDeleted()` then add `ON CLUSTER`, and the migrations history table becomes a `ReplicatedMergeTree` table that all hosts share, so all hosts agree on which migrations are applied. In a database with the `Replicated` engine, which refuses `ON CLUSTER`, use `UseReplicatedMigrationsHistoryTable()` instead. Note that a Replicated table ignores an insert with the same rows as a recent insert. See "Replication and Clusters" in the README, which also shows how to convert an existing history table. ([#71](https://github.com/ClickHouse/ClickHouse.EntityFrameworkCore/issues/71))

### Query translation
* **Large `Contains` filters work.** A filter such as `Where(x => ids.Contains(x.Id))` now sends the whole list as one ClickHouse array parameter (``x.Id IN {ids:Array(Int64)}``) instead of one parameter for each value. ClickHouse refuses a request with more than 1,000 fields by default, so a list of about 1,000 values failed. Now the limit is the size of one parameter value, 128 KiB by default, and the driver sends it URL-encoded: about 10,000 `Int64` values of 10 digits, 5,900 of 19 digits, or 2,900 GUIDs. To raise it, set `http_max_field_value_size` in the `default` profile of the server configuration, restart the server, and add `UseFormDataParameters=true` to the connection string. `HashSet<T>`, lazy sequences and lists that contain `null` work too. Nullable columns, enums and values such as `TimeSpan` keep one parameter for each value. To get one parameter for each value, use `EF.MultipleParameters(ids)` for one query or `UseParameterizedCollectionMode(ParameterTranslationMode.MultipleParameters)` for all queries; `EF.Constant(ids)` writes the values into the SQL. ([#39](https://github.com/ClickHouse/ClickHouse.EntityFrameworkCore/issues/39))
* **`toStartOf*` date-time functions** are now translatable through `EF.Functions`, covering the full family: `ToStartOfYear`, `ToStartOfQuarter`, `ToStartOfMonth`, `ToStartOfWeek` (with an optional ClickHouse week `mode`), `ToStartOfDay`, `ToStartOfHour`, `ToStartOfMinute`, `ToStartOfSecond`, the fixed buckets `ToStartOfFiveMinutes` / `ToStartOfTenMinutes` / `ToStartOfFifteenMinutes`, and the general-purpose `ToStartOfInterval(source, value, unit)`. They compose in `GROUP BY` for time bucketing. Input and return types follow ClickHouse: the calendar buckets (`ToStartOfYear`/`Quarter`/`Month`/`Week`) return `Date`, `ToStartOfDay` and the hour/minute buckets return `DateTime`, and `ToStartOfSecond` returns `DateTime64`. All accept `DateTime`/`DateTime64` columns, and the plain truncation functions also accept `DateOnly` (Date/Date32); `ToStartOfInterval` is the exception — older ClickHouse rejects a `DateOnly` (Date/Date32) source with `Illegal type Date32 of 1st argument`, while recent versions accept it, so prefer a `DateTime`/`DateTime64` column for interval bucketing. `ToStartOfInterval` uses a `ClickHouseInterval` enum for the unit and is emitted as `toStartOfInterval(source, toInterval<unit>(value))`. Because the default result types (`Date`/`DateTime`) only span 1970–2149/2106, ClickHouse narrows out-of-range values (pre-1970 clamps to the epoch or wraps around); enable `enable_extended_results_for_datetime_functions` in your session (e.g. `set_enable_extended_results_for_datetime_functions=1` in the connection string) to get range-preserving `Date32`/`DateTime64` results.

### Bug fixes
* A query that compares one value with two columns of different ClickHouse types, for example a `String` column and a `LowCardinality(String)` column, no longer fails with `No value was provided for the required parameter`.
* **Settings you set in code now apply when you pass a `ClickHouseConnection` or `ClickHouseDataSource` to `UseClickHouse`.** Settings that have no connection-string key, such as `SkipServerCertificateValidation`, `BearerToken`, `CustomHeaders` or a custom `HttpClient`, were lost when the provider opened the connection or created the database. For example, a server with a self-signed certificate failed with an untrusted-root error even with `SkipServerCertificateValidation = true`. They are now kept on every path, including `EnsureCreated`, `EnsureDeleted` and migrations. The provider also no longer changes the connection or data source that you pass in: it adds `join_use_nulls=1` to each statement that it sends. A context that uses a `ClickHouseDataSource` therefore shares the HTTP connections of the data source instead of opening its own. A command that you run yourself through `Database.GetDbConnection()` does not get `join_use_nulls=1`; set it in your connection settings if you need it. If you wrap the connection in a different `DbConnection` type, for example for profiling, the provider still adds the setting to its connection string, and the code-only settings are lost. Use an EF Core command interceptor that wraps the command in `CommandCreated` for profiling instead: the setting is then kept. ([#50](https://github.com/ClickHouse/ClickHouse.EntityFrameworkCore/issues/50))
* Scripts from `dotnet ef migrations script` now run in `clickhouse-client`. Before, statements such as `ALTER TABLE ... ADD COLUMN` had no `;` at the end, so the client read two statements as one and stopped with a syntax error. Applying migrations from code (`Database.Migrate()`, `dotnet ef database update`) was not affected.
* `ToStartOfWeek` now rejects row-dependent week modes during query translation, and `ToStartOfInterval` likewise rejects row-dependent interval sizes. ClickHouse requires these operands to be constant for the query; literals and captured query parameters remain supported.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Data.Common;
using ClickHouse.EntityFrameworkCore.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.DependencyInjection;

Expand Down Expand Up @@ -32,6 +33,14 @@
/// </summary>
public bool ReplicatedMigrationsHistoryTable { get; private set; }

/// <summary>
/// The mode that the application set with <c>UseParameterizedCollectionMode</c>, or <see langword="null"/>
/// when it did not set one. <see cref="RelationalOptionsExtension.ParameterizedCollectionMode"/> returns
/// <see cref="ParameterTranslationMode.MultipleParameters"/> in both cases. With no explicit mode, the
/// provider sends a captured collection in <c>Contains</c> as one array parameter.
/// </summary>
public ParameterTranslationMode? ExplicitParameterizedCollectionMode { get; private set; }

public ClickHouseOptionsExtension()
{
}
Expand All @@ -43,6 +52,7 @@
JoinNullSemanticsDisabled = copyFrom.JoinNullSemanticsDisabled;
ClusterName = copyFrom.ClusterName;
ReplicatedMigrationsHistoryTable = copyFrom.ReplicatedMigrationsHistoryTable;
ExplicitParameterizedCollectionMode = copyFrom.ExplicitParameterizedCollectionMode;
}

protected override RelationalOptionsExtension Clone()
Expand Down Expand Up @@ -76,6 +86,14 @@
return clone;
}

public override RelationalOptionsExtension WithUseParameterizedCollectionMode(
ParameterTranslationMode parameterizedCollectionMode)
{
var clone = (ClickHouseOptionsExtension)base.WithUseParameterizedCollectionMode(parameterizedCollectionMode);
clone.ExplicitParameterizedCollectionMode = parameterizedCollectionMode;
return clone;
}

public override RelationalOptionsExtension WithConnectionString(string? connectionString)
{
var clone = (ClickHouseOptionsExtension)base.WithConnectionString(connectionString);
Expand All @@ -83,7 +101,7 @@
return clone;
}

public override RelationalOptionsExtension WithConnection(DbConnection? connection, bool contextOwnsConnection = false)

Check warning on line 104 in src/EFCore.ClickHouse/Infrastructure/Internal/ClickHouseOptionsExtension.cs

View workflow job for this annotation

GitHub Actions / .NET 10.0

In member RelationalOptionsExtension ClickHouseOptionsExtension.WithConnection(DbConnection? connection, bool contextOwnsConnection = false), change parameter name contextOwnsConnection to owned in order to match the identifier as it has been declared in RelationalOptionsExtension RelationalOptionsExtension.WithConnection(DbConnection? connection, bool owned) (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1725)
{
var clone = (ClickHouseOptionsExtension)base.WithConnection(connection, contextOwnsConnection);
clone.DataSource = null;
Expand All @@ -103,12 +121,26 @@
{
}

private new ClickHouseOptionsExtension Extension
=> (ClickHouseOptionsExtension)base.Extension;

public override bool IsDatabaseProvider => true;

public override string LogFragment => string.Empty;

// IClickHouseSingletonOptions holds ExplicitParameterizedCollectionMode, so a context with a
// different value needs a different service provider.
public override int GetServiceProviderHashCode()
=> Extension.ExplicitParameterizedCollectionMode?.GetHashCode() ?? 0;

public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other)
=> other is ExtensionInfo otherInfo
&& Extension.ExplicitParameterizedCollectionMode == otherInfo.Extension.ExplicitParameterizedCollectionMode;

public override void PopulateDebugInfo(IDictionary<string, string> debugInfo)
{
if (Extension.ExplicitParameterizedCollectionMode is { } mode)
debugInfo["ClickHouse:ExplicitParameterizedCollectionMode"] = mode.ToString();
}
}
}
Loading
Loading