DuckDbSharp is a bidirectional interoperability layer between DuckDB and .NET.
Features
[Flags]
enumsIEnumerable<>
Notes:
This is not an ADO.NET (System.Data) provider
Exporting methods as scalar functions is not supported, only as table functions (DuckDB doesn't currently provide C APIs for that)
-- my_query.sql
SELECT
42 AS column1,
[1, 2, 3] AS column2,
[{a: 1, b: 2}] as column3
foreach (var user in db.ExecuteQuery_my_query())
{
// "user" has an auto-generated type with all the fields and sub-fields of the SQL query above.
}
See detailed instructions below.
using var db = ThreadSafeTypedDuckDbConnection.CreateInMemory();
foreach (var user in db.Execute<User>("select * from user"))
{
}
You can also use value tuples (Execute<(string A, int B)>("select 'a', 42")
), but keep in mind that only column order matters, since tuple member names are erased at runtime.
[DuckDbFunction]
public static IEnumerable<User> GetUsers(string country) { /*...*/ }
SELECT * FROM GetUsers('US')
DuckDbSharp
.sql
queries you want to be able to call from .NET
ReturnType query_name(paramtype1, paramtype2).sql
ReturnType
is not specified, a type will be automatically generated based on the SQL schema of the result.string
or long
). Otherwise, parens are unnecessary.GenerateCSharpTypes
as shown in the example, and run.TypedDuckDbConnectionBase
(one for each query).Time to read ~100,000 rows of Northwind customers. In all 4 cases, the final result is a List<Customer> . |
Library | Mean | Error | StdDev | Description |
---|---|---|---|---|---|
DuckDbSharp (this project) | 145.4 ms | 2.63 ms | 2.46 ms | SELECT * FROM customer | |
DuckDB.NET + Dapper | 177.2 ms | 2.88 ms | 2.69 ms | SELECT * FROM customer | |
Protobuf-net | 131.3 ms | 2.52 ms | 2.81 ms | Deserialize from MemoryStream of protos | |
Newtonsoft JSON | 241.7 ms | 2.93 ms | 2.60 ms | Deserialize from MemoryStream of JSON |
Note: while protobuf-net is slightly faster, its use cases is very different (serialization/deserialization only, with no query support)
[DuckDbInclude]
and [DuckDbIgnore]
always take the precedence over other rules. In their absence, [ProtoMember]
from protobuf-net is also taken into account. Otherwise, only public fields and properties are taken into account.[DuckDbSerializeAs(typeof(string))]
or [DuckDbSerializeAs(typeof(int))]
(or whatever their underlying type is).[Flags]
enums are always serialized as structs of booleans, one for each bit.[DuckDbDefaultValueIsNullish]
can be applied to structs, and it means that default(SomeStruct)
should be represented as NULL
in DuckDB.
DuckDbUtils.QueryParquet<T>()
and DuckDbUtils.WriteParquet<T>()
to directly read/write .parquet
files (no database required).