Path: redb/redb.Tests.Integration/Tests/Sqlite/SqliteKeyCacheRepeatTests.cs
Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb
Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Tests.Integration/Tests/Sqlite/SqliteKeyCacheRepeatTests.cs
----
using AwesomeAssertions.Execution;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using redb.Core;
using redb.Core.Data;
using redb.Core.Extensions;
using redb.Core.Models.Entities;
using redb.Export.Providers;
using redb.Export.Services;
using redb.SQLite.Extensions;
using redb.Tests.Integration.Fixtures;
using redb.Tests.Integration.Models;
namespace redb.Tests.Integration.Tests.Sqlite;
///
/// The key cache of a process is kept per domain, and the domain is the hash of the connection string, not the
/// database. Two cases where the cache hands out an id another row already has:
///
/// - two connection strings to one SQLite file in one process: the mark that keeps a range handed out in a
/// rolled-back transaction from being handed out again is per string, so the other string repeats the range;
/// - an import into a database the process already used: the block the process cached before the import is
/// handed out over the imported rows.
///
/// The save looked new objects up as existing after it had given them their ids, so a repeated id did not fail: the
/// create updated the row that had the id. Objects the save gives an id are now inserted; a repeated id fails once with
/// a clear error, the cache of the domain is reset and the next save takes a fresh range. An id the caller set is still
/// saved onto the row that has it (save by id): the two cases built on such an id are limits of 4.8 and skipped.
///
public class SqliteKeyCacheRepeatTests
{
private const string SequenceTopSql = "SELECT seq FROM sqlite_sequence WHERE name = '_global_identity'";
[Fact(Skip = "Limit of 4.8: the key domain is the connection string, so the mark of ids handed out in a rolled-back " +
"transaction is per string; an id the caller kept is then handed out under the other string and saving it " +
"by id writes over that row.")]
public async Task TwoConnectionStringsToOneFile_ARangeRolledBackUnderOne_IsNotHandedOutAgainUnderTheOther()
{
var file = $"redb_tests_keydomain_{Guid.NewGuid():N}.db";
var csA = $"Data Source={file}";
var csB = $"Data Source={Path.GetFullPath(file)}";
SqliteTestSupport.DeleteDbFiles(csA);
await using var providerA = Build(csA);
await using var providerB = Build(csB);
var a = providerA.GetRequiredService();
var b = providerB.GetRequiredService();
await a.InitializeAsync(ensureCreated: true);
await a.SyncSchemeAsync();
await b.InitializeAsync();
await b.SyncSchemeAsync();
((RedbKeyGeneratorBase)a.Context.Keys).Domain.Should().NotBe(((RedbKeyGeneratorBase)b.Context.Keys).Domain,
"precondition: the two strings name one file and give two key domains");
// Under string A: an id the application takes inside its own transaction, which then rolls back.
long held;
await using (var tx = await a.Context.BeginTransactionAsync())
{
RedbKeyGeneratorBase.ClearAllCaches();
var top = await a.Context.ExecuteScalarAsync(SequenceTopSql);
held = (await a.Context.NextObjectIdBatchAsync(1))[0];
held.Should().BeGreaterThan(top, "precondition: the id came from inside the transaction");
await tx.RollbackAsync();
}
// Under string B: its next range (its cache ran out, which emptying the caches stands for).
RedbKeyGeneratorBase.ClearAllCaches();
var victim = new RedbObject { name = "keydomain-B", Props = new SimpleProps { Title = "written by B" } };
var victimId = await b.SaveAsync(victim);
// Under string A again: the application saves its object with the id it kept.
var kept = new RedbObject { name = "keydomain-A", Props = new SimpleProps { Title = "written by A" } };
kept.Id = held;
await a.SaveAsync(kept);
var victimNow = await b.LoadAsync(victimId);
using (new AssertionScope())
{
victimId.Should().NotBe(held, "an id handed out under string A is not handed out again under string B");
victimNow!.name.Should().Be("keydomain-B", "saving A's object does not write over B's row");
victimNow.Props.Title.Should().Be("written by B");
}
}
[Fact]
public async Task ImportIntoADatabaseTheProcessUsed_TheNextSave_FailsOnceAndLeavesTheImportedRows()
{
var (target, source) = (NewDatabase("tgt"), NewDatabase("src"));
await using var providerT = Build(target);
var redb = providerT.GetRequiredService();
await SeedAsync(redb, 1);
var importedIds = await SeedSourceAndImportAsync(source, target, 20);
// The block this process cached before the import is still handed out: the create gets an imported id.
var created = new RedbObject { name = "keyimport-new", Props = new SimpleProps { Title = "after the import" } };
var first = async () => await redb.SaveAsync(created);
await first.Should().ThrowAsync().WithMessage("*key cache*restore or an import*");
created.Id.Should().Be(0, "the failed save gives the object its id 0 back");
await AssertImportedIntactAsync(target, importedIds);
// The cache was reset: the same object is created with a fresh id.
var id = await redb.SaveAsync(created);
importedIds.Should().NotContain(id);
(await redb.LoadAsync(id))!.Props.Title.Should().Be("after the import");
await AssertImportedIntactAsync(target, importedIds);
}
[Fact]
public async Task ImportIntoADatabaseTheProcessUsed_TheNextAddNewObjects_FailsOnceAndLeavesTheImportedRows()
{
var (target, source) = (NewDatabase("tgt"), NewDatabase("src"));
await using var providerT = Build(target);
var redb = providerT.GetRequiredService();
await SeedAsync(redb, 1);
var importedIds = await SeedSourceAndImportAsync(source, target, 20);
var created = new RedbObject { name = "keyimport-bulk", Props = new SimpleProps { Title = "bulk after the import" } };
var first = async () => await redb.AddNewObjectsAsync(new[] { created });
await first.Should().ThrowAsync().WithMessage("*key cache*restore or an import*");
created.Id.Should().Be(0);
await AssertImportedIntactAsync(target, importedIds);
var ids = await redb.AddNewObjectsAsync(new[] { created });
importedIds.Should().NotContain(ids[0]);
(await redb.LoadAsync(ids[0]))!.Props.Title.Should().Be("bulk after the import");
await AssertImportedIntactAsync(target, importedIds);
}
private static async Task AssertImportedIntactAsync(string target, List importedIds)
{
var names = await ScalarAsync(target,
$"SELECT COUNT(*) FROM _objects WHERE _name LIKE 'keyimport-src-%' AND _id IN ({string.Join(",", importedIds)})");
names.Should().Be(importedIds.Count.ToString(), "every imported object keeps its row");
}
[Fact(Skip = "Limit of 4.8 by design: an id the caller set is saved onto the row that has it (save by id). An id taken " +
"before an import and saved after it writes over the imported row; restart the application after an import.")]
public async Task ImportIntoADatabaseTheProcessUsed_AnIdTakenBefore_DoesNotWriteOverAnImportedRow()
{
var (target, source) = (NewDatabase("tgt"), NewDatabase("src"));
await using var providerT = Build(target);
var redb = providerT.GetRequiredService();
await SeedAsync(redb, 1);
var held = (await redb.Context.NextObjectIdBatchAsync(1))[0];
var importedIds = await SeedSourceAndImportAsync(source, target, 20);
importedIds.Should().Contain(held, "precondition: the imported rows took the id the process had already handed out");
var importedName = await ScalarAsync(target, $"SELECT _name FROM _objects WHERE _id = {held}");
var kept = new RedbObject { name = "keyimport-kept", Props = new SimpleProps { Title = "taken before the import" } };
kept.Id = held;
await redb.SaveAsync(kept);
(await ScalarAsync(target, $"SELECT _name FROM _objects WHERE _id = {held}")).Should().Be(importedName,
"an object saved with an id taken before the import does not write over the imported row of that id");
}
private static async Task SeedAsync(IRedbService redb, int count)
{
await redb.InitializeAsync(ensureCreated: true);
await redb.SyncSchemeAsync();
for (var i = 0; i < count; i++)
await redb.SaveAsync(new RedbObject { name = $"keyimport-tgt-{i}", Props = new SimpleProps { Title = $"t{i}" } });
}
///
/// A second database built by the same steps hands out the same ids; it saves more objects, so its rows cover
/// the ids the target process holds next. Exported and imported into the target with cleaning, the way a backup
/// of another installation is loaded.
///
private static async Task> SeedSourceAndImportAsync(string source, string target, int count)
{
await using (var provider = Build(source))
{
var src = provider.GetRequiredService();
await src.InitializeAsync(ensureCreated: true);
await src.SyncSchemeAsync();
for (var i = 0; i < count; i++)
await src.SaveAsync(new RedbObject { name = $"keyimport-src-{i}", Props = new SimpleProps { Title = $"s{i}" } });
}
var file = Path.Combine(Path.GetTempPath(), $"redb-export-{Guid.NewGuid():N}.redb");
await using (var provider = ProviderFactory.Create("sqlite"))
{
await provider.OpenAsync(source);
await new ExportService(provider, verbose: false, batchSize: 1000).ExportAsync(file, null, compress: false, dryRun: false);
}
await using (var provider = ProviderFactory.Create("sqlite"))
{
await provider.OpenAsync(target);
await new ImportService(provider, verbose: false, batchSize: 1000).ImportAsync(file, clean: true, dryRun: false);
}
File.Delete(file);
var ids = new List();
await using var connection = new SqliteConnection(target);
await connection.OpenAsync();
await using var command = connection.CreateCommand();
command.CommandText = "SELECT _id FROM _objects WHERE _name LIKE 'keyimport-src-%'";
await using var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
ids.Add(reader.GetInt64(0));
return ids;
}
private static string NewDatabase(string suffix)
{
var cs = $"Data Source=redb_tests_keyimport_{suffix}_{Guid.NewGuid():N}.db";
SqliteTestSupport.DeleteDbFiles(cs);
return cs;
}
private static ServiceProvider Build(string cs)
{
global::redb.SQLite.Data.SqliteDataSource.NativeExtensionPath ??= SqliteTestSupport.ResolveNativeExtension();
var services = new ServiceCollection();
services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning));
services.AddRedb(options =>
{
options.UseSqlite(cs);
options.Configure(c => c.CacheDomain = $"keycache-{Guid.NewGuid():N}");
});
return services.BuildServiceProvider();
}
private static async Task ScalarAsync(string cs, string sql)
{
await using var connection = new SqliteConnection(cs);
await connection.OpenAsync();
await using var command = connection.CreateCommand();
command.CommandText = sql;
return (await command.ExecuteScalarAsync())?.ToString();
}
}