EFCore.DuckDB¶
An EF Core 10 relational provider for DuckDB. Package ID:
JonesGaffney.EntityFrameworkCore.DuckDB; root namespace:
JonesGaffney.EntityFrameworkCore.DuckDB. Targets .NET 10, EF Core 10.0.14,
and DuckDB.NET.Data.Full 1.5.6.1 (bundled DuckDB 1.5.6).
This is an initial provider implementation. Consult VALIDATION.md for the
validation actually completed in this checkout before using it with real data.
Licensing is pending Andrew's decision; see LICENSE-PENDING.md.
Usage¶
Reference src/EFCore.DuckDB/EFCore.DuckDB.csproj while developing the unpublished
package. The normal EF extensions live in Microsoft.EntityFrameworkCore.
using Microsoft.EntityFrameworkCore;
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseDuckDB("Data Source=app.duckdb", duckdb => duckdb.CommandTimeout(30))
.Options;
await using var db = new AppDbContext(options);
await db.Database.EnsureCreatedAsync();
db.Notes.Add(new Note { Text = "Hello DuckDB" });
await db.SaveChangesAsync();
Console.WriteLine(await db.Notes.CountAsync());
public sealed class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public DbSet<Note> Notes => Set<Note>();
}
public sealed class Note
{
public int Id { get; set; }
public string Text { get; set; } = "";
}
Use Data Source=:memory: for a database private to one context. The provider
keeps its in-memory connection alive across EF operations and disposes it with
the context. To share one in-memory database between contexts, open a
DuckDB.NET.Data.DuckDBConnection yourself and pass it to UseDuckDB(connection);
the caller owns that connection unless contextOwnsConnection: true is supplied.
Do not use one connection or context concurrently.
For application DI, use services.AddDbContext<AppDbContext>(o =>
o.UseDuckDB(connectionString)). services.AddEntityFrameworkDuckDB() is also
provided for applications that explicitly build EF's internal service provider.
EnsureCreated/EnsureDeleted support local files and in-memory databases.
Automatic file deletion currently supports Windows only, where the provider
excludes other readers and writers before unlinking the database/WAL. It refuses
to delete a file still in use. On other operating systems, stop all database
users and delete files offline. Shared-cache memory databases must be deleted by
closing every connection, rather than by calling EnsureDeleted.
Choose EnsureCreated for disposable schemas or Database.Migrate() for
versioned migrations; do not mix those lifecycle strategies on one database.
Type mapping¶
| CLR type | DuckDB type |
|---|---|
bool |
BOOLEAN |
sbyte, short, int, long |
TINYINT, SMALLINT, INTEGER, BIGINT |
byte, ushort, uint, ulong |
UTINYINT, USMALLINT, UINTEGER, UBIGINT |
float, double |
FLOAT, DOUBLE |
decimal |
DECIMAL(18,2) by default; configure .HasPrecision(p, s) |
string |
VARCHAR |
byte[] |
BLOB |
Guid |
UUID |
DateTime |
TIMESTAMP |
DateTimeOffset |
TIMESTAMPTZ |
DateOnly, TimeOnly, TimeSpan |
DATE, TIME, INTERVAL |
| enums | EF value conversion to their underlying type, or .HasConversion<string>() |
Decimal precision is at most 38, with scale between 0 and precision. Choose
facets appropriate to the domain; the default (18,2) cannot preserve arbitrary
CLR decimal values. Strings are unbounded; DuckDB does not enforce a VARCHAR(n)
length as a validation rule.
Temporal columns have microsecond precision. DateTime, DateTimeOffset, TimeOnly
and TimeSpan values are truncated (floored) to whole microseconds in both
parameters and SQL literals, matching DuckDB itself (TIMESTAMP '2020-01-01
00:00:00.1234567' stores .123456), so DateTime.UtcNow can be saved directly.
Consequence: the value read back can differ from the CLR value by up to 9 ticks.
A client-assigned DateTime concurrency token therefore no longer equals its stored
value after SaveChanges; re-read the entity after saving before reusing the token.
TIMESTAMP does not preserve DateTime.Kind; TIMESTAMPTZ preserves an instant,
not the original UTC offset. Use UTC when interpreting timestamp values across
machines. SQL literals use invariant formatting, escaped text, typed temporal
literals, and hexadecimal BLOB decoding.
DuckDB.NET 1.5.6.1 truncates bound strings at U+0000. The provider rejects such
parameters before execution; this includes saved strings and query parameters.
SQL literal generation supports embedded NUL with chr(0). Use BLOB for
arbitrary bytes rather than silently truncating text.
Queries and writes¶
Implemented translations include Contains, StartsWith, EndsWith,
ToLower, ToUpper, Trim, Length, Substring, Replace, IsNullOrEmpty,
Math.Abs/Round/Floor/Ceiling/Max/Min, DateTime.Now/UtcNow/Year/Month/Day,
Guid.NewGuid(), and EF.Functions.Like. SQL uses quoted identifiers,
LIMIT/OFFSET, || concatenation, and CAST.
Parameters use DuckDB's supported $name syntax (such as $p0) with bare
ADO.NET parameter names. Named parameters allow EF to reuse a parameter safely;
they are the driver's named variant of $1 positional parameters.
Integer division uses DuckDB //. Decimal Math.Round uses exact decimal
arithmetic for constant digit counts; floating-point rounding uses round_even.
These follow ties-to-even rather than DuckDB's ordinary round tie behavior.
String comparison overloads and dynamic decimal rounding precision are not
translated. String indexing and length follow DuckDB Unicode characters rather
than CLR UTF-16 code units. Date/time functions use the server/session timezone
and transaction clock; they are not a client machine clock.
Inserts retrieve generated values with RETURNING. Updates with generated
values and deletes also use RETURNING; ordinary updates check the driver's
affected-row count. DuckDB rewrites UPDATE … RETURNING as delete/insert and
rejects it when other rows reference the updated row, even if its key is unchanged.
Avoid update-generated columns on referenced parent tables. Stale concurrency
tokens throw DbUpdateConcurrencyException. Configure tokens with .IsConcurrencyToken() and
update application-managed tokens yourself; an automatic SQL Server-style
rowversion is not available. Writes use one modification command per batch.
Conventional generated integer primary keys use a sequence and a
DEFAULT nextval(...) expression. Sequence names include a deterministic hash
of schema/table/column identity. Explicit ValueGeneratedNever, explicit
defaults, and foreign-key keys are respected. DuckDB sequences have signed
64-bit range even when the mapped column is unsigned.
Transactions and foreign keys¶
DuckDB MVCC transactions support commit and rollback. Savepoints are not
supported: SupportsSavepoints returns false, EF does not create automatic
savepoints, and explicit savepoint operations throw NotSupportedException.
After a failed SaveChanges in a caller-owned transaction, roll back the entire
transaction before further work.
DuckDB foreign keys must be declared in CREATE TABLE. An EF migration that
adds an FK to an existing table throws a clear exception; write and review an
explicit table-rebuild migration instead. Database cascading actions are not
supported. Required relationships default to EF client-side cascade behavior;
load dependents before deleting, or explicitly manage dependent rows. DuckDB's
immediate FK checks still apply during each statement.
Migrations and reviewed scripts¶
Add Microsoft.EntityFrameworkCore.Design 10.0.14 to your application and use a
matching dotnet-ef tool. Normal migrations can be applied with
Database.Migrate() or generated with dotnet ef migrations script.
Supported operations include tables, columns (including renames), schemas,
indexes, sequence creation/deletion, inline FK constraints, and basic column
type/nullability/default alterations where DuckDB permits the change.
Virtual generated columns in CREATE TABLE are supported with
.HasComputedColumnSql(expression, stored: false) and are returned after
inserts/updates. Stored generated columns and adding generated columns to an
existing table are not supported.
Required-column additions use separate ADD COLUMN and SET NOT NULL
statements. With no default, a numeric default or a string default they share one
migration command. With any other default (bool, DateTime, Guid and other typed
literals, or defaultValueSql such as CURRENT_TIMESTAMP) DuckDB rewrites the existing
rows and then refuses SET NOT NULL in the same transaction ("Cannot create index with
outstanding updates"), so SET NOT NULL is emitted as its own transaction-suppressed
command: EF commits the ADD COLUMN first and runs SET NOT NULL after it. Such a
migration is not all-or-nothing; if SET NOT NULL fails the column stays nullable and the
migration is not recorded in the history table.
Table renames, column renames and column type changes fail in DuckDB while the table has
any index. The generator reads the migration's target model, drops the table's indexes
before the first such operation and recreates them (on the new table and column names)
after the batch. Indexes the same batch creates or drops are left alone. A type change
and any UNIQUE index recreate use transaction-suppressed commands because DuckDB will not
see a dropped index as gone, or rebuild a unique index under the same name, within one
transaction; those migrations are likewise not all-or-nothing. Index renames
(RenameIndex, for example when a column rename changes a conventional index name)
remain unsupported. Other expression defaults or dependent FKs still require an explicit
reviewed table rebuild.
HasData seed rows carry explicit keys and never advance the key sequence, so the
conventional sequence for a generated integer key starts at the highest seeded key plus
one. This applies to models built (or migrations generated) with this version; a database
created earlier keeps its sequence starting at 1, so run CREATE OR REPLACE SEQUENCE
"<name>" START WITH <max key + 1>; once by hand (find the name with
SELECT sequence_name FROM duckdb_sequences();). CREATE OR REPLACE resets the counter,
so only do this before new keys are generated. Adding HasData to a model that already
has a migration snapshot makes EF diff the sequence start value into a
RestartSequence operation, which this provider reports as unsupported; replace it in
the migration with migrationBuilder.Sql("CREATE OR REPLACE SEQUENCE ...").
Migration history defaults to __EFMigrationsHistory; customize it through
duckdb.MigrationsHistoryTable(name, schema).
DuckDB has no procedural IF around arbitrary DDL. Therefore an idempotent script
uses provider history directives and must run through the supplied C# runner.
It is not a standalone SQL script for the DuckDB CLI. A guard deliberately fails
if the script is sent directly to DuckDB, preventing unguarded migration replay.
dotnet ef migrations script --idempotent --output migrations.sql
dotnet run --project tools/EFCore.DuckDB.Migrate -c Release -- --connection "Data Source=app.duckdb" --script migrations.sql
The runner also accepts --script - for standard input and
--history-table/--history-schema to match the generating context. Only execute
trusted, reviewed scripts. It interprets history guards, honors transaction
boundaries, and rolls back the active transaction on failure. Applications may
also call DuckDBMigrationScriptRunner.ExecuteAsync(context, script, token).
Forward-only versioned SQL can remain in git and run as reviewed jobs.
EF migrations and the runner acquire a durable singleton row in
__EFMigrationsLock. Acquisition times out using the command timeout (30 seconds
by default); async acquisition supports cancellation. A process crash can leave
a stale row. Verify that no migrator is running before manually clearing the
lock table. The provider never steals or automatically expires a lock.
Quack¶
Configure a closed in-memory connection and supply credentials from your secret store, not source control:
options.UseDuckDB("Data Source=:memory:",
duckdb => duckdb.UseQuack("quack:localhost", tokenFromSecretStore));
DuckDBQuackConnectionInterceptor opens the remote catalog with
ATTACH 'quack:host' AS app (TOKEN '...'); USE app;. It quotes both literals,
bypasses EF command logging for attachment, and replaces driver initialization
errors with a message that excludes SQL, token, and inner exceptions. Do not add
external driver tracing that records secret-bearing ATTACH statements.
Persistent local connections are rejected. Remote database deletion is not
supported; manage the server lifecycle separately.
After initialization failure or cancellation, dispose the context/connection
and create a new one. A failed connection is quarantined to prevent subsequent
operations from silently using its local catalog.
Starting with 0.1.2, UseQuack inlines parameters as SQL literals using the
provider's type mappings before execution. Raw SQL supports named dollar
placeholders such as $name and $1; positional ? placeholders are rejected.
The lexer preserves quoted strings, quoted identifiers, and comments, and
rejects missing or unused parameters before sending SQL. Command diagnostics
retain the original parameterized SQL. Driver error details are suppressed
because they may contain inlined personal data. This applies only to Quack;
local parameter binding and its embedded-NUL restriction remain unchanged.
Quack literals support embedded NUL through chr(0).
Quack TLS¶
duckdb.UseQuack("quack:10.10.0.10:9494", token, q => q.SslFingerprint = "<64 hex sha256 of leaf cert DER>");
SslFingerprint pins the server leaf certificate (colons and upper case are accepted and
normalised) and emits DISABLE_SSL false, SSL_FINGERPRINT '...'. DisableSsl = true sends
plaintext and works only against a disable_ssl=true server; it cannot be combined with a
fingerprint. CA-file trust was not verified to work and is not offered.
Quack requires compatible client/server protocol support. The package pins the
driver requested in the brief; setting UseQuack cannot add protocol support to
a native library that lacks it. The integration test runs only with a local
loopback QUACK_TEST_URI and QUACK_TEST_TOKEN; otherwise it is skipped.
Build and test¶
dotnet restore --configfile NuGet.Config --disable-parallel
dotnet build -c Release -m:1
dotnet test -c Release -m:1
The SDK is pinned to the .NET 10.0.3xx stable feature band. Tests use xUnit and disable collection parallelism to limit native database and host memory use. The suite covers type literals/parameters, SQL generation, CRUD, relationships, owned values, conversions, concurrency, transactions, database creation, migrations, idempotent script replay, and optional Quack attachment.
Not yet supported¶
- Standalone pure-SQL idempotent scripts; use the C# runner.
- Automatic file deletion outside Windows and deletion of shared-cache memory databases.
- Savepoints, database FK cascades, FK alteration, and arbitrary constraint alteration.
- Sequence alteration/restart/rename; sequence values beyond signed
BIGINTrange. - Stored generated columns, adding generated columns, and some column alterations with dependent FKs or expression defaults.
- Moving tables between schemas, filtered/descending indexes, and index renames.
- Database reverse engineering (
dotnet ef dbcontext scaffold). - Automatic rowversion, stored procedures, JSON/complex DuckDB types, and complete EF provider parity.
- Sub-microsecond temporal precision (values are truncated), original timestamp offsets/kinds, and full CLR string semantics.
- Embedded NUL in string parameters (driver limitation), and generated-value updates on referenced parent rows.
- The EF relational specification suite has not been wired; no specification pass rate is claimed.