clickhouse-cs / ClickHouse.Driver
AGENTS.md102 starsChanged 2 months agoMITView on GitHub
These rules add to the root AGENTS.md. They apply to ClickHouse.Driver/, ClickHouse.Driver.Tests/ and ClickHouse.Driver.IntegrationTests/. This project also builds the ClickHouse.Driver NuGet package, which contains the native TCP client and ClickHouse.Driver.Common. The TCP client has its own rules in ClickHouse.Driver.Tcp/AGENTS.md. ClickHouseClient (recommended): ClickHouseConnection (for ORMs): Key differences: - ClickHouseClient: Thread-safe, can be singleton, has InsertBinaryAsync for bulk inserts - ClickHouseConnection: ADO.NET DbConnection, required for ORM compatibility - ClickHouseBulkCopy: Deprecated - use ClickHouseClient.InsertBinaryAsync instead - Read and write: When making changes to…
- Deletes or force-pushes
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 35,117 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository12 other files it gives its agents.
- AGENTS.mdAGENTS.md
- ClickHouse.Driver.Tcp/AGENTS.mdAGENTS.md
- examples/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- ClickHouse.Driver/CLAUDE.mdCLAUDE.md
- ClickHouse.Driver.Tcp/CLAUDE.mdCLAUDE.md
- examples/CLAUDE.mdCLAUDE.md
- .github/copilot-instructions.mdCopilot instructions
- reviewSkill
- issue-classificationSkill
- issue-prioritySkill
- reviewSkill
The file
We split this AGENTS.md into the rules it gives an agent
7 rules. About 0 are common, 2 are distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 71
Read and write: When making changes to types, consider both the binary read and write paths in the type class itself, as well as the HTTP …
- Distinctive: line 78
ADO.NET compliance: Follow ADO.NET patterns and interfaces correctly
- Very specific: line 83
Parameters: Use ClickHouseParameterCollection with ClickHouseDbParameter for parameterized queries
- Very specific: line 128
If the value is null/DBNull and no explicit type or hint is provided, resolution falls through to Nullable(Nothing).
- Distinctive: line 173
Do not set it to a version other than that of the server you point the suite at.
- Very specific: line 199
Keep it (with a DROP) solely in the [SetUp] of a fixture that deliberately shares one table.
- Very specific: line 214
Test utilities: before writing tests, read Utilities/TestUtilities.cs to understand existing config and utility patterns, including …
≈ “Common” is an estimate: at least 1 in 5 of the 45,344 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
HTTP client (ClickHouse.Driver)
These rules add to the root AGENTS.md. They apply to ClickHouse.Driver/,
ClickHouse.Driver.Tests/ and ClickHouse.Driver.IntegrationTests/.
This project also builds the ClickHouse.Driver NuGet package, which contains the native TCP client
and ClickHouse.Driver.Common. The TCP client has its own rules in
ClickHouse.Driver.Tcp/AGENTS.md.
Project Context
- Primary API:
ClickHouseClient- thread-safe, singleton-friendly, recommended for most use cases - ADO.NET API:
ClickHouseConnection/ClickHouseCommand- for ORM compatibility (Dapper, EF Core, linq2db) - Targets:
net6.0,net8.0,net9.0,net10.0. Tests run on all four;ClickHouse.Driver.IntegrationTestsruns onnet10.0.
Structure
ClickHouse.Driver/
├── ClickHouseClient.cs, QueryOptions.cs, InsertOptions.cs # Primary API
├── Utility/ # Schema, feature detection, extension methods
├── ADO/ # ADO.NET layer (Connection, Command, DataReader, Parameters)
├── Types/ # 60+ ClickHouse type implementations + TypeConverter.cs
├── Copy/ # Binary serialization (used internally by ClickHouseClient)
├── Formats/ # RowBinary readers/writers, HttpParameterFormatter
├── Http/ # HTTP layer & connection pooling
└── PublicAPI/ # Public API surface tracking (hand-maintained)Key Files
- Primary API:
ClickHouseClient.cs- main entry point for most applications - Type system:
Types/TypeConverter.cs(complex),Types/Grammar/(type parsing) - ADO.NET layer:
ADO/ClickHouseConnection.cs,ADO/ClickHouseCommand.cs,ADO/Readers/ - Feature detection:
Utility/ClickHouseFeatureMap.cs(version-based capabilities) - Parameter formatting:
Formats/HttpParameterFormatter.cs - Public API:
PublicAPI/*.txt(hand-maintained record of shipped signatures; theMicrosoft.CodeAnalysis.PublicApiAnalyzerspackage is not referenced by this project, so nothing checks these files at build time. Keep them in sync yourself.) - Config:
.editorconfig(file-scoped namespaces, StyleCop suppressions)
API Architecture
ClickHouseClient (recommended):
using var client = new ClickHouseClient("Host=localhost");
await client.ExecuteNonQueryAsync("CREATE TABLE ...");
await client.InsertBinaryAsync(tableName, columns, rows); // High-performance bulk insert
using var reader = await client.ExecuteReaderAsync("SELECT ...");
var scalar = await client.ExecuteScalarAsync("SELECT count() ...");ClickHouseConnection (for ORMs):
// Use ClickHouseDataSource for proper connection lifetime management with ORMs
var dataSource = new ClickHouseDataSource("Host=localhost");
services.AddSingleton(dataSource);
// Dapper, EF Core, linq2db work with DbConnection
using var connection = dataSource.CreateConnection();
var users = connection.Query<User>("SELECT * FROM users");Key differences:
ClickHouseClient: Thread-safe, can be singleton, hasInsertBinaryAsyncfor bulk insertsClickHouseConnection: ADO.NETDbConnection, required for ORM compatibilityClickHouseBulkCopy: Deprecated - useClickHouseClient.InsertBinaryAsyncinstead
Development Guidelines
- Read and write: When making changes to types, consider both the binary read and write paths in
the type class itself, as well as the HTTP parameter write path in
HttpParameterFormatter.cs. The TCP client has a copy of that formatter (see "Logic that exists in both clients" in the root file). - ClickHouse version support: Respect
FeatureSwitch,ClickHouseFeatureMapfor multi-version compatibility - Hot paths: Core code in
ADO/,Types/,Utility/- avoid allocations, boxing, unnecessary copies - Connection pooling: Respect HTTP connection pool behavior, avoid connection leaks
- ADO.NET compliance: Follow ADO.NET patterns and interfaces correctly
Configuration & Settings
- Client configuration: Connection string or
ClickHouseClientSettingsfor client-level settings - Per-query options:
QueryOptionsfor query-specific settings (QueryId, CustomSettings, Roles, BearerToken) - Parameters: Use
ClickHouseParameterCollectionwithClickHouseDbParameterfor parameterized queries
// Client-level settings
var settings = new ClickHouseClientSettings("Host=localhost");
settings.CustomSettings.Add("max_threads", 4);
using var client = new ClickHouseClient(settings);
// Per-query options
var options = new QueryOptions
{
QueryId = "my-query-id",
CustomSettings = new Dictionary<string, object> { ["max_execution_time"] = 30 },
};
await client.ExecuteReaderAsync("SELECT ...", options: options);
// Parameters
var parameters = new ClickHouseParameterCollection();
parameters.AddParameter("id", 42UL);
await client.ExecuteReaderAsync("SELECT * FROM t WHERE id = {id:UInt64}", parameters);Query Parameters
Two parameter syntaxes are supported:
- ClickHouse-native
{name:Type}: sent verbatim to the server. Preferred when writing queries by hand. - ADO.NET-style
@name: purely client-side. Rewritten to{name:ResolvedType}before the request is sent (ClickHouse never sees@). Required for ORMs like Dapper that emit@-style placeholders.
Both refer to parameters by name in ClickHouseParameterCollection. A {name:Type} hint and an
@name placeholder for the same parameter are compatible; the hint informs type resolution.
Type resolution precedence (first match wins, in ADO/Parameters/ParameterTypeResolution.cs):
- Explicit
ClickHouseDbParameter.ClickHouseTypeon the parameter object - SQL type hint from
{name:Type}in the query - Custom
IParameterTypeResolver(per-queryQueryOptions.ParameterTypeResolver, then client-levelClickHouseClientSettings.ParameterTypeResolver) decimalspecial case:Decimal128(scale)where scale is read from the value's bits.ClickHouseDecimalspecial case:Decimal128(9)if it holds the value exactly, else the value's scale without trailing zeros (raised to 9 where there is room) inDecimal128or, above 38 digits,Decimal256TypeConverter.ToClickHouseType(value): inferred from the .NET runtime value (not just the static type, so e.g.IPAddressis disambiguated intoIPv4/IPv6byAddressFamily)
If the value is null/DBNull and no explicit type or hint is provided, resolution falls through to
Nullable(Nothing). Whether the server accepts that null sentinel depends on the expected
column/type context; non-nullable targets may reject it. For nullable parameters, set
ClickHouseType explicitly or include a {name:Nullable(T)} hint.
DbType on ClickHouseDbParameter is not part of the precedence chain; only ClickHouseType is.
Setting DbType alone does not influence the resolved ClickHouse type.
Data flow (in ClickHouseClient.PostSqlQueryAsync):
ClickHouseParameterCollection.ResolveTypeNames(sql, resolver)extracts{name:Type}hints viaSqlParameterTypeExtractor(string/comment-aware), then runs the precedence chain once per parameter. Conflicting hints for the same name throw.ClickHouseParameterCollection.ReplacePlaceholders(sql, resolved)rewrites every@nameto{name:ResolvedType}. Bypassable via theClickHouse.Driver.DisableReplacingParametersAppContext switch.HttpParameterFormatter.Format(parameter, resolvedType, settings, customFormatter)does culture-invariant value formatting for all 60+ types. Top-levelnull/DBNullparameter values become\Nand skip the custom formatter; nullable values inside composite contexts may instead be emitted as the literalnullby the type-specific formatter.IParameterFormatter(per-query or client-level) can override formatting; transparent wrappers (Nullable,LowCardinality,Variant) are unwrapped before the formatter is called.- Values are sent as
param_<name>either in the URI query string (default) or as multipart form fields whenClickHouseClientSettings.UseFormDataParametersis true.
When changing parameter behavior, update both the read and write paths: the type's binary
serialization in Types/ and the HTTP write path in Formats/HttpParameterFormatter.cs.
Testing
Running tests
dotnet test ClickHouse.Driver.Tests --framework net9.0 --property WarningLevel=0The suite uses the server in CLICKHOUSE_CONNECTION (an HTTP connection string). When that is not
set and CLICKHOUSE_TEST_ENVIRONMENT is unset or local_single_node, it starts a ClickHouse
container with Testcontainers, which needs Docker. CLICKHOUSE_TEST_ENVIRONMENT names the kind of
server (see TestEnv in Utilities/TestUtilities.cs).
CLICKHOUSE_VERSION selects the container image tag, and it is also the version the version gates
use. The suite asks the server for its version only when the variable is unset, latest or head.
Do not set it to a version other than that of the server you point the suite at.
Table names
Any test that touches a table must get its name from CreateTableName(...) (see the root file for
why):
// In a fixture deriving from AbstractConnectionTestFixture (preferred, cleans up for you):
var table = CreateTableName(); // test.MyTestMethod_net9_a1b2c3d4e5f6
// Anywhere else (you own the cleanup):
var table = TestUtilities.CreateTableName(); // + DROP TABLE IF EXISTS in your teardown- The inherited
AbstractConnectionTestFixture.CreateTableName()registers the name so[OneTimeTearDown]drops it. Prefer it over the static helper whenever the fixture allows. - Pass a prefix only to carry a parametrized case, e.g.
CreateTableName($"bulk_{clickHouseType}"). Prefixes are sanitized, so interpolating type names, timezone ids etc. is safe; no manual scrubbing needed. - Names are already
test.-qualified. Never prependtest.yourself. Passdatabase: "other_db"to target another database, ordatabase: nullfor an unqualified name (required forCREATE TEMPORARY TABLE, which cannot be qualified). - Because every name is unique, a plain
CREATE TABLEcannot collide. Don't addIF NOT EXISTS, don'tDROPbefore theCREATE, and don't wrap a test intry/finallyjust to drop its table.IF NOT EXISTSon a unique name only hides a future isolation regression. Keep it (with aDROP) solely in the[SetUp]of a fixture that deliberately shares one table. - Gotcha: the server stores the unqualified name, so a test comparing against
system.tables/system.columns/DESCRIBEoutput, or against a table name in an exception message, must split it:var bare = name[(name.IndexOf('.') + 1)..];. - Gotcha: passing a qualified name to an API whose database resolution you are testing (e.g.
InsertOptions.Database,QueryOptions.Database) makes the override a no-op and silently voids the assertion. Pass the bare name there, keeping the qualified one for read-back. - A fixture may deliberately share one table across its tests and reset it in
[SetUp]; that is fine. Hoist oneCreateTableName(...)into the fixture rather than splitting it per test. Utilities/TestTableNamingTests.cspins this contract; keep it passing.
Suite conventions
- Type matrix:
Utilities/TestCases.cs(GetDataTypeSamples()) already round-trips every type, plus itsNullable/Array/composite forms, through the select, parameter, bulk-copy and serialisation suites. - Test utilities: before writing tests, read
Utilities/TestUtilities.csto understand existing config and utility patterns, includingCreateTableName/SanitizeTableName. - Clients for a real server: get them from
TestUtilities.GetTestClickHouseClient()/GetTestClickHouseConnection()orAbstractConnectionTestFixture. A test that makes its ownClickHouseClientSettingsmust setCustomHeaders = TestUtilities.GetTestCustomHeaders(). On Cloud, these headers keep every request of the run on one replica; without them, a session, aMemorytable or a read of a row that the test just inserted can reach another replica and fail. A connection string cannot carry the headers, so use the settings constructor. system.query_log:QueryLog.ScalarAsyncfails with a distinct message when no row appears;QueryLog.CountAsyncwaits forminimumCountrows before reporting.- Server version gating:
[FromVersion],[IgnoreInVersion]and[RequiredFeature]inAttributes/. - Test matrix: ADO provider, parameter binding, ORMs, multi-framework, multi-ClickHouse-version
- Test organization: Client tests in
ClickHouse.Driver.Tests, third-party integration tests inClickHouse.Driver.IntegrationTests
Documentation
User-facing behavior of this client is documented in docs/http.mdx.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

