Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion DuckDB.NET.Data/DuckDBConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,10 @@ public override void ChangeDatabase(string databaseName)

public override void Close()
{
// DbConnection.Close: "An application can call Close or CloseAsync more than one time. No exception is generated."
if (connectionState == ConnectionState.Closed)
{
throw new InvalidOperationException("Connection is already closed.");
return;
}

if (connectionReference is not null) //Should always be the case
Expand Down
20 changes: 14 additions & 6 deletions DuckDB.NET.Test/DuckDBConnectionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,30 +53,38 @@ public async Task ConnectionSpeed()
files.Dispose();
}

// https://learn.microsoft.com/dotnet/api/system.data.common.dbconnection.close:
// "An application can call Close or CloseAsync more than one time. No exception is generated."
[Fact]
[Trait("Category", "Baseline")]
public async Task ExceptionOnDoubleClose()
public async Task CloseCanBeCalledMoreThanOnce()
{
using var dbInfo = DisposableFile.GenerateInTemp("db");
await using var duckDBConnection = new DuckDBConnection(dbInfo.ConnectionString);
await duckDBConnection.OpenAsync();
var stateChanges = 0;
duckDBConnection.StateChange += (_, _) => stateChanges++;

await duckDBConnection.CloseAsync();
await duckDBConnection.Invoking(async connection => await connection.CloseAsync())
.Should().ThrowAsync<InvalidOperationException>();
await duckDBConnection.CloseAsync();
duckDBConnection.Close();

duckDBConnection.State.Should().Be(ConnectionState.Closed);
stateChanges.Should().Be(1, "only the first Close changes the state");
}

[Fact]
[Trait("Category", "Baseline")]
public async Task ExceptionOnDisposeThenClose()
public async Task CloseAfterDisposeDoesNotThrow()
{
using var dbInfo = DisposableFile.GenerateInTemp("db");
await using var duckDBConnection = new DuckDBConnection(dbInfo.ConnectionString);
await duckDBConnection.OpenAsync();

await duckDBConnection.DisposeAsync();
await duckDBConnection.Invoking(async connection => await connection.CloseAsync())
.Should().ThrowAsync<InvalidOperationException>();
await duckDBConnection.CloseAsync();

duckDBConnection.State.Should().Be(ConnectionState.Closed);
}

/// <summary>
Expand Down
Loading