diff --git a/bindings/dotnet/Readme.md b/bindings/dotnet/Readme.md index a5b88dfce..e3936620d 100644 --- a/bindings/dotnet/Readme.md +++ b/bindings/dotnet/Readme.md @@ -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`. | diff --git a/bindings/dotnet/src/Turso.Data.Sqlite/SqliteConnection.cs b/bindings/dotnet/src/Turso.Data.Sqlite/SqliteConnection.cs index ae51d69b4..857e9d5f0 100644 --- a/bindings/dotnet/src/Turso.Data.Sqlite/SqliteConnection.cs +++ b/bindings/dotnet/src/Turso.Data.Sqlite/SqliteConnection.cs @@ -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() - { - } + /// + /// Closes every pooled database that has no open connection. Databases still in use close + /// when their last connection does. + /// + public static void ClearAllPools() => SqliteConnectionPool.ClearAll(); + /// + /// Closes the pooled database used by once it has no open + /// connection. + /// 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; diff --git a/bindings/dotnet/src/Turso.Data.Sqlite/SqliteConnectionPool.cs b/bindings/dotnet/src/Turso.Data.Sqlite/SqliteConnectionPool.cs new file mode 100644 index 000000000..9ebdcafb7 --- /dev/null +++ b/bindings/dotnet/src/Turso.Data.Sqlite/SqliteConnectionPool.cs @@ -0,0 +1,134 @@ +using Turso.Raw.Public; +using Turso.Raw.Public.Handles; + +namespace Turso.Data.Sqlite; + +/// +/// Keeps local database files open between connections when Pooling is enabled. +/// +/// +/// Opening a native database reads the schema and replays the WAL, which dominates the cost of +/// . The pool keeps one opened database per file and gives each +/// 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 . +/// +internal static class SqliteConnectionPool +{ + private static readonly object Gate = new(); + private static readonly Dictionary 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 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; + } + } + } +} diff --git a/bindings/dotnet/src/Turso.Tests/SqliteFacadeTests.cs b/bindings/dotnet/src/Turso.Tests/SqliteFacadeTests.cs index f92b18a02..297f93632 100644 --- a/bindings/dotnet/src/Turso.Tests/SqliteFacadeTests.cs +++ b/bindings/dotnet/src/Turso.Tests/SqliteFacadeTests.cs @@ -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("PRAGMA foreign_keys;").Should().Be(1); + } + + using var second = new SqliteConnection($"Data Source={path}"); + second.Open(); + second.ExecuteScalar("PRAGMA foreign_keys;").Should().Be(0); + second.ExecuteScalar("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("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("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(() => connection.Open()); + + File.Delete(path); + File.Exists(path).Should().BeFalse(); + + using var reopened = new SqliteConnection($"Data Source={path}"); + reopened.Open(); + reopened.ExecuteScalar("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); } diff --git a/bindings/dotnet/src/Turso.Tests/TursoEfCoreTests.cs b/bindings/dotnet/src/Turso.Tests/TursoEfCoreTests.cs index caf82389a..051352ff2 100644 --- a/bindings/dotnet/src/Turso.Tests/TursoEfCoreTests.cs +++ b/bindings/dotnet/src/Turso.Tests/TursoEfCoreTests.cs @@ -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"))