From e1c327c9e17fb84b68d27a435997d2baafa0c412 Mon Sep 17 00:00:00 2001 From: "Dailey, Alaric" Date: Tue, 20 Oct 2026 06:45:33 -0500 Subject: [PATCH] Prepare requires an open connection IDbCommand.Prepare documents InvalidOperationException when "The Connection is not set. -or- The Connection is not Open()." Prepare was an empty method, so a command with no usable connection passed it and failed only when it executed. Co-Authored-By: Claude Opus 5.5 --- DuckDB.NET.Data/DuckDBCommand.cs | 6 +++++- DuckDB.NET.Test/DuckDBCommandTests.cs | 16 +++++++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/DuckDB.NET.Data/DuckDBCommand.cs b/DuckDB.NET.Data/DuckDBCommand.cs index 6d602614..bed08427 100644 --- a/DuckDB.NET.Data/DuckDBCommand.cs +++ b/DuckDB.NET.Data/DuckDBCommand.cs @@ -164,7 +164,11 @@ public async IAsyncEnumerable ExecuteArrowBatchesAsync([EnumeratorC } } - public override void Prepare() { } + /// + /// Statements are prepared when the command executes, so this only checks what IDbCommand.Prepare documents: + /// InvalidOperationException when "The Connection is not set. -or- The Connection is not Open()." + /// + public override void Prepare() => EnsureConnectionOpen(); protected override DbParameter CreateDbParameter() => new DuckDBParameter(); diff --git a/DuckDB.NET.Test/DuckDBCommandTests.cs b/DuckDB.NET.Test/DuckDBCommandTests.cs index b807f2b6..f4ec9a0a 100644 --- a/DuckDB.NET.Test/DuckDBCommandTests.cs +++ b/DuckDB.NET.Test/DuckDBCommandTests.cs @@ -17,4 +17,18 @@ public void SetCommandTextAndConnection() cmd.CommandText.Should().Be("Select 1"); cmd.Connection.Should().Be(Connection); } -} \ No newline at end of file + + // https://learn.microsoft.com/dotnet/api/system.data.idbcommand.prepare, Exceptions: InvalidOperationException, + // "The Connection is not set. -or- The Connection is not Open()." + [Fact] + public void PrepareThrowsWithoutAnOpenConnection() + { + new DuckDBCommand("SELECT 1").Invoking(c => c.Prepare()).Should().Throw(); + + using var closed = new DuckDBConnection(DuckDBConnectionStringBuilder.InMemoryConnectionString); + new DuckDBCommand("SELECT 1", closed).Invoking(c => c.Prepare()).Should().Throw(); + + new DuckDBCommand("SELECT 1", Connection).Invoking(c => c.Prepare()).Should().NotThrow(); + } +} +