ClickHouse allows passing arbitrary tables along with a query. In ClickHouseClient, these are managed via the TableProviders collection on a ClickHouseCommand.
To implement a custom table, implement the IClickHouseTableProvider interface. The library provides a default implementation, ClickHouseTableProvider, which allows you to build tables in a columnar format similar to ClickHouseColumnWriter.
How to use ClickHouseTableProvider:
- Instantiate
ClickHouseTableProvider with a table name and the expected row count. - Use
.AddColumn(name, data) to add columns. Column settings (like ClickHouseDbType or IsNullable) can be configured on the returned column object. - Add the provider to
cmd.TableProviders. - Reference the table name directly in your SQL query without special syntax.
using var connection = new ClickHouseConnection(connectionStr);
connection.Open();
var cmd = connection.CreateCommand("SELECT ptable.id, ptable.user, ptable.ip FROM ptable");
var users = new[] {"user1", "user2", "admin1", "admin2"};
var ips = new[] {"1.1.1.1", "2.2.2.2", "127.0.0.1", "::ffff:192.0.2.1"};
var pTableProvider = new ClickHouseTableProvider("ptable", users.Length);
pTableProvider.AddColumn("id", Enumerable.Range(1, users.Length));
pTableProvider.AddColumn("user", users);
// Configure column settings
var ipColumn = pTableProvider.AddColumn("ip", ips);
ipColumn.ClickHouseDbType = ClickHouseDbType.IpV6;
ipColumn.IsNullable = false;
cmd.TableProviders.Add(pTableProvider);
using var reader = cmd.ExecuteReader();
while(reader.Read())
{
// Reading the data
}