mirror of
https://github.com/allankoechke/turso.git
synced 2026-11-30 11:12:58 +00:00
bindings/dotnet: pool local databases in Turso.Data.Sqlite
SqliteConnection had no pool: ClearAllPools and ClearPool were empty, and every Open created, opened and connected a new native database. The core only shares a Database while one of its connections is alive, and closing the last connection runs a full checkpoint. With one connection per operation, every Open re-read the schema and replayed the WAL, and every Close checkpointed. Add SqliteConnectionPool, which keeps one opened database per full path (case-insensitive on Windows). With Pooling=True, the existing builder default, each Open gets a fresh native connection on the pooled database, so PRAGMAs, functions, temp state and open transactions never leak between opens. Each entry also holds one idle anchor connection so the database's connection count never drops to zero and Close no longer checkpoints every time. ClearPool and ClearAllPools now release pool entries. A database that still has open connections closes when the last one does. Entries are also released on AppDomain.ProcessExit so the WAL gets its final checkpoint. :memory: and shared in-memory databases, which are temp files deleted when their last connection closes, are never pooled. As with Microsoft.Data.Sqlite, a pooled file stays open after Close, so on Windows it cannot be deleted or replaced until ClearPool or ClearAllPools is called. EnsureDeleted already calls ClearAllPools. Tests that delete database files now call ClearAllPools first, and the Readme describes the Pooling keyword. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -259,7 +259,7 @@ Supported common connection string keywords include:
|
||||
| `Foreign Keys` | Parsed and preserved for compatibility. |
|
||||
| `Recursive Triggers` | Parsed and preserved for compatibility. |
|
||||
| `Default Timeout` | Used as the default command timeout. Aliases include `Command Timeout`. |
|
||||
| `Pooling` | Parsed and preserved for compatibility. |
|
||||
| `Pooling` | Defaults to `True`. Local files stay open after the last connection closes so the next `Open()` skips reloading the schema and WAL; each connection still gets fresh connection state. Call `SqliteConnection.ClearPool` or `ClearAllPools` before deleting or replacing a pooled file. `:memory:` and shared in-memory databases are never pooled. |
|
||||
| `Vfs` | Parsed and preserved for compatibility. |
|
||||
| `Encryption Cipher` | Turso local encryption cipher. |
|
||||
| `Encryption Key` | Hex-encoded encryption key used with `Encryption Cipher`. |
|
||||
|
||||
@@ -170,7 +170,9 @@ public partial class SqliteConnection : DbConnection
|
||||
var sharedMemoryPath = IsSharedMemory(_connectionOptions) ? RegisterSharedMemoryFile(filename) : null;
|
||||
try
|
||||
{
|
||||
_database = TursoBindings.OpenDatabase(filename);
|
||||
_database = CanPool(_connectionOptions, filename, sharedMemoryPath)
|
||||
? SqliteConnectionPool.Connect(filename)
|
||||
: TursoBindings.OpenDatabase(filename);
|
||||
_dataSource = filename;
|
||||
_readOnly = readOnly;
|
||||
_sharedMemoryPath = sharedMemoryPath;
|
||||
@@ -318,13 +320,35 @@ public partial class SqliteConnection : DbConnection
|
||||
throw new ArgumentException(Properties.Resources.UnknownCollection(collectionName));
|
||||
}
|
||||
|
||||
public static void ClearAllPools()
|
||||
{
|
||||
}
|
||||
/// <summary>
|
||||
/// Closes every pooled database that has no open connection. Databases still in use close
|
||||
/// when their last connection does.
|
||||
/// </summary>
|
||||
public static void ClearAllPools() => SqliteConnectionPool.ClearAll();
|
||||
|
||||
/// <summary>
|
||||
/// Closes the pooled database used by <paramref name="connection" /> once it has no open
|
||||
/// connection.
|
||||
/// </summary>
|
||||
public static void ClearPool(SqliteConnection connection)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(connection);
|
||||
var filename = connection._dataSource;
|
||||
if (filename is null && connection._connectionOptions.IsLocal)
|
||||
{
|
||||
try
|
||||
{
|
||||
filename = NormalizeDataSource(connection._connectionOptions);
|
||||
}
|
||||
catch (SqliteException)
|
||||
{
|
||||
// A file that cannot be opened has nothing pooled.
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (filename is not null && !IsMemoryLike(filename))
|
||||
SqliteConnectionPool.Clear(filename);
|
||||
}
|
||||
|
||||
public new virtual SqliteTransaction BeginTransaction()
|
||||
@@ -1137,6 +1161,14 @@ public partial class SqliteConnection : DbConnection
|
||||
private static string QuoteIdentifier(string identifier)
|
||||
=> "\"" + identifier.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"";
|
||||
|
||||
// Shared in-memory databases are temp files deleted when their last connection closes, so
|
||||
// they must not outlive it in the pool.
|
||||
private static bool CanPool(SqliteConnectionStringBuilder options, string filename, string? sharedMemoryPath)
|
||||
=> options.Pooling && sharedMemoryPath is null && !IsMemoryLike(filename);
|
||||
|
||||
private static bool IsMemoryLike(string filename)
|
||||
=> filename.StartsWith(":memory:", StringComparison.Ordinal);
|
||||
|
||||
private static bool IsSharedMemory(SqliteConnectionStringBuilder options)
|
||||
=> options.Mode == SqliteOpenMode.Memory && options.Cache == SqliteCacheMode.Shared && options.DataSource.Length > 0;
|
||||
|
||||
|
||||
134
bindings/dotnet/src/Turso.Data.Sqlite/SqliteConnectionPool.cs
Normal file
134
bindings/dotnet/src/Turso.Data.Sqlite/SqliteConnectionPool.cs
Normal file
@@ -0,0 +1,134 @@
|
||||
using Turso.Raw.Public;
|
||||
using Turso.Raw.Public.Handles;
|
||||
|
||||
namespace Turso.Data.Sqlite;
|
||||
|
||||
/// <summary>
|
||||
/// Keeps local database files open between connections when <c>Pooling</c> is enabled.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Opening a native database reads the schema and replays the WAL, which dominates the cost of
|
||||
/// <see cref="SqliteConnection.Open"/>. The pool keeps one opened database per file and gives each
|
||||
/// <see cref="SqliteConnection"/> a fresh native connection on it, so per-connection state such as
|
||||
/// PRAGMAs, functions and temp tables never leaks between opens. Each entry also holds one idle
|
||||
/// anchor connection: closing the last connection to a database checkpoints the whole WAL, and the
|
||||
/// anchor keeps that from happening on every <see cref="SqliteConnection.Close"/>.
|
||||
/// </remarks>
|
||||
internal static class SqliteConnectionPool
|
||||
{
|
||||
private static readonly object Gate = new();
|
||||
private static readonly Dictionary<string, Entry> Entries = new(
|
||||
OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
|
||||
private static bool _processExitHooked;
|
||||
|
||||
public static TursoDatabaseHandle Connect(string filename)
|
||||
{
|
||||
var key = Path.GetFullPath(filename);
|
||||
while (true)
|
||||
{
|
||||
Entry? entry;
|
||||
lock (Gate)
|
||||
{
|
||||
if (!Entries.TryGetValue(key, out entry))
|
||||
{
|
||||
entry = new Entry();
|
||||
Entries.Add(key, entry);
|
||||
}
|
||||
|
||||
if (!_processExitHooked)
|
||||
{
|
||||
// Close idle databases on exit so their WAL is checkpointed, as it would be
|
||||
// when the last connection closes without a pool.
|
||||
AppDomain.CurrentDomain.ProcessExit += (_, _) => ClearAll();
|
||||
_processExitHooked = true;
|
||||
}
|
||||
}
|
||||
|
||||
lock (entry)
|
||||
{
|
||||
if (entry.Cleared)
|
||||
continue;
|
||||
|
||||
if (entry.Database is null)
|
||||
{
|
||||
TursoSharedDatabaseHandle? database = null;
|
||||
try
|
||||
{
|
||||
database = TursoBindings.OpenSharedDatabase(filename);
|
||||
entry.Anchor = TursoBindings.Connect(database);
|
||||
}
|
||||
catch
|
||||
{
|
||||
database?.Dispose();
|
||||
RemoveFailedEntry(key, entry);
|
||||
throw;
|
||||
}
|
||||
|
||||
entry.Database = database;
|
||||
}
|
||||
|
||||
return TursoBindings.Connect(entry.Database);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Called with the entry lock held. Taking Gate here is safe because Gate is never held
|
||||
// while waiting for an entry lock. Marking the entry cleared sends connections waiting on
|
||||
// it back to the dictionary, so none of them opens a database on an entry that is no
|
||||
// longer reachable from ClearPool.
|
||||
private static void RemoveFailedEntry(string key, Entry entry)
|
||||
{
|
||||
entry.Cleared = true;
|
||||
lock (Gate)
|
||||
{
|
||||
if (Entries.TryGetValue(key, out var current) && ReferenceEquals(current, entry))
|
||||
Entries.Remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Clear(string filename)
|
||||
{
|
||||
var key = Path.GetFullPath(filename);
|
||||
Entry? entry;
|
||||
lock (Gate)
|
||||
{
|
||||
if (!Entries.Remove(key, out entry))
|
||||
return;
|
||||
}
|
||||
|
||||
entry.Release();
|
||||
}
|
||||
|
||||
public static void ClearAll()
|
||||
{
|
||||
List<Entry> entries;
|
||||
lock (Gate)
|
||||
{
|
||||
entries = [.. Entries.Values];
|
||||
Entries.Clear();
|
||||
}
|
||||
|
||||
foreach (var entry in entries)
|
||||
entry.Release();
|
||||
}
|
||||
|
||||
private sealed class Entry
|
||||
{
|
||||
public TursoSharedDatabaseHandle? Database;
|
||||
public TursoDatabaseHandle? Anchor;
|
||||
public bool Cleared;
|
||||
|
||||
// Connections still open on this database keep it alive until they close.
|
||||
public void Release()
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
Cleared = true;
|
||||
Anchor?.Dispose();
|
||||
Database?.Dispose();
|
||||
Anchor = null;
|
||||
Database = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -323,6 +323,88 @@ public class SqliteFacadeTests
|
||||
exception!.SqliteErrorCode.Should().Be(8);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PooledConnectionsDoNotShareConnectionState()
|
||||
{
|
||||
using var directory = new TemporaryDirectory();
|
||||
var path = Path.Combine(directory.Path, "pooled-state.db");
|
||||
using (var first = new SqliteConnection($"Data Source={path}"))
|
||||
{
|
||||
first.Open();
|
||||
first.ExecuteNonQuery("CREATE TABLE Data(Value INTEGER); PRAGMA foreign_keys = ON;");
|
||||
first.ExecuteScalar<long>("PRAGMA foreign_keys;").Should().Be(1);
|
||||
}
|
||||
|
||||
using var second = new SqliteConnection($"Data Source={path}");
|
||||
second.Open();
|
||||
second.ExecuteScalar<long>("PRAGMA foreign_keys;").Should().Be(0);
|
||||
second.ExecuteScalar<long>("SELECT COUNT(*) FROM Data;").Should().Be(0);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ClosingPooledConnectionRollsBackOpenTransaction()
|
||||
{
|
||||
using var directory = new TemporaryDirectory();
|
||||
var path = Path.Combine(directory.Path, "pooled-rollback.db");
|
||||
using (var setup = new SqliteConnection($"Data Source={path}"))
|
||||
{
|
||||
setup.Open();
|
||||
setup.ExecuteNonQuery("CREATE TABLE Data(Value INTEGER);");
|
||||
}
|
||||
|
||||
using (var writer = new SqliteConnection($"Data Source={path}"))
|
||||
{
|
||||
writer.Open();
|
||||
writer.ExecuteNonQuery("BEGIN; INSERT INTO Data VALUES (1);");
|
||||
}
|
||||
|
||||
using var reader = new SqliteConnection($"Data Source={path}");
|
||||
reader.Open();
|
||||
reader.ExecuteScalar<long>("SELECT COUNT(*) FROM Data;").Should().Be(0);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ClearPoolReleasesDatabaseFiles()
|
||||
{
|
||||
using var directory = new TemporaryDirectory();
|
||||
var path = Path.Combine(directory.Path, "pooled-clear.db");
|
||||
using (var connection = new SqliteConnection($"Data Source={path}"))
|
||||
{
|
||||
connection.Open();
|
||||
connection.ExecuteNonQuery("CREATE TABLE Data(Value INTEGER); INSERT INTO Data VALUES (1);");
|
||||
connection.Close();
|
||||
SqliteConnection.ClearPool(connection);
|
||||
}
|
||||
|
||||
File.Delete(path);
|
||||
File.Delete(path + "-wal");
|
||||
File.Exists(path).Should().BeFalse();
|
||||
|
||||
using var reopened = new SqliteConnection($"Data Source={path}");
|
||||
reopened.Open();
|
||||
reopened.ExecuteScalar<long>("SELECT COUNT(*) FROM sqlite_master;").Should().Be(0);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FailedPooledOpenDoesNotKeepFileOpen()
|
||||
{
|
||||
using var directory = new TemporaryDirectory();
|
||||
var path = Path.Combine(directory.Path, "pooled-not-a-database.db");
|
||||
var garbage = new byte[8192];
|
||||
Array.Fill(garbage, (byte)0x5A);
|
||||
File.WriteAllBytes(path, garbage);
|
||||
|
||||
using (var connection = new SqliteConnection($"Data Source={path}"))
|
||||
Assert.Throws<SqliteException>(() => connection.Open());
|
||||
|
||||
File.Delete(path);
|
||||
File.Exists(path).Should().BeFalse();
|
||||
|
||||
using var reopened = new SqliteConnection($"Data Source={path}");
|
||||
reopened.Open();
|
||||
reopened.ExecuteScalar<long>("SELECT COUNT(*) FROM sqlite_master;").Should().Be(0);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void StateChangeFiresForOpenAndClose()
|
||||
{
|
||||
@@ -1184,6 +1266,7 @@ public class SqliteFacadeTests
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
SqliteConnection.ClearAllPools();
|
||||
if (Directory.Exists(Path))
|
||||
Directory.Delete(Path, recursive: true);
|
||||
}
|
||||
|
||||
@@ -275,6 +275,8 @@ public class TursoEfCoreTests
|
||||
await using var context = CreateContext(database.ConnectionString);
|
||||
await context.Database.EnsureCreatedAsync();
|
||||
await context.Database.CloseConnectionAsync();
|
||||
// The pool keeps the database (and its WAL) open after the connection closes.
|
||||
SqliteConnection.ClearAllPools();
|
||||
|
||||
var walPath = database.Path + "-wal";
|
||||
var shmPath = database.Path + "-shm";
|
||||
@@ -399,6 +401,7 @@ public class TursoEfCoreTests
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
SqliteConnection.ClearAllPools();
|
||||
if (File.Exists(Path))
|
||||
File.Delete(Path);
|
||||
if (File.Exists(Path + "-wal"))
|
||||
|
||||
Reference in New Issue
Block a user