Path: redb/redb.Tests.Integration/Tests/Base/MigrationTestsBase.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/Base/MigrationTestsBase.cs
----
using System.Globalization;
using Microsoft.Extensions.DependencyInjection;
using redb.Core;
using redb.Core.Exceptions;
using redb.Core.Models.Entities;
using redb.Core.Pro.Migration;
using redb.Core.Pro.Query;
using redb.Tests.Integration.Models;
namespace redb.Tests.Integration.Tests.Base;
///
/// Pro data-migration suite (ComputedFrom): apply, idempotency, dry-run and history.
///
/// Written because this feature had no test coverage on any provider, which is why a real defect
/// went unnoticed: on SQLite the _migrations history table was never created (PG/MSSql get it
/// from the concatenated redb_init.sql, SQLite has no such concatenation), so the executor's very
/// first statement — the idempotency probe — failed with "no such table".
///
///
public abstract class MigrationTestsBase
{
protected readonly IRedbService Redb;
private readonly ISqlDialectPro _dialect;
protected MigrationTestsBase(IRedbService redb, IServiceProvider services)
{
Redb = redb;
_dialect = services.GetRequiredService();
}
///
/// Clears the migration history for this scheme so each test starts from a known state
/// (the executor is idempotent by design — a leftover row would make it skip).
///
private async Task ResetAsync()
{
var scheme = await Redb.SyncSchemeAsync();
await Redb.Context.ExecuteAsync($"DELETE FROM _migrations WHERE _scheme_id = {scheme.Id}");
await Redb.Context.ExecuteAsync(
$"DELETE FROM _values WHERE _id_object IN (SELECT _id FROM _objects WHERE _id_scheme = {scheme.Id})");
await Redb.Context.ExecuteAsync($"DELETE FROM _objects WHERE _id_scheme = {scheme.Id}");
return scheme.Id;
}
private async Task SeedAsync(long quantity, double price)
{
var obj = new RedbObject
{
name = $"migration-probe-{quantity}x{price}",
Props = new MigrationProbeProps { Quantity = quantity, Price = price, TotalPrice = 0 }
};
obj.id = await Redb.SaveAsync(obj);
return obj.id;
}
private Task HistoryCountAsync(long schemeId) =>
Redb.Context.ExecuteScalarAsync(
$"SELECT COUNT(*) FROM _migrations WHERE _scheme_id = {schemeId}");
[Fact]
public async Task Migrate_ComputedFrom_RecalculatesTheField()
{
await ResetAsync();
var id = await SeedAsync(quantity: 3, price: 10.5);
var results = await Redb.MigrateAsync(_dialect);
results.Should().NotBeEmpty();
results.Should().OnlyContain(r => r.Success, "a failing migration reports Success=false with Error set");
var loaded = await Redb.LoadAsync(id);
loaded!.Props.TotalPrice.Should().BeApproximately(31.5, 0.0001);
}
[Fact]
public async Task Migrate_WritesHistoryRow()
{
var schemeId = await ResetAsync();
await SeedAsync(quantity: 2, price: 4);
(await HistoryCountAsync(schemeId)).Should().Be(0);
await Redb.MigrateAsync(_dialect, appliedBy: "tests");
(await HistoryCountAsync(schemeId)).Should().Be(1, "applying a migration must record it in _migrations");
}
[Fact]
public async Task Migrate_Twice_IsIdempotent()
{
var schemeId = await ResetAsync();
await SeedAsync(quantity: 5, price: 2);
await Redb.MigrateAsync(_dialect);
var second = await Redb.MigrateAsync(_dialect);
second.Should().OnlyContain(r => r.Success);
second.Should().Contain(r => r.Skipped, "the history row must make the second run a no-op");
(await HistoryCountAsync(schemeId)).Should().Be(1, "a skipped run must not add a second row");
}
[Fact]
public async Task Migrate_DryRun_ChangesNothing()
{
var schemeId = await ResetAsync();
var id = await SeedAsync(quantity: 7, price: 3);
var results = await Redb.MigrateAsync(_dialect, dryRun: true);
results.Should().OnlyContain(r => r.Success);
var loaded = await Redb.LoadAsync(id);
loaded!.Props.TotalPrice.Should().Be(0, "dry-run must not touch the data");
(await HistoryCountAsync(schemeId)).Should().Be(0, "dry-run must not record an applied migration");
}
// ---- DefaultValue, Transform, and ComputedFrom onto a [RedbUnique] field ----
/// Empties a scheme of the suite: its history, values and objects.
private async Task ResetSchemeAsync() where TProps : class, new()
{
var scheme = await Redb.SyncSchemeAsync();
await Redb.Context.ExecuteAsync($"DELETE FROM _migrations WHERE _scheme_id = {scheme.Id}");
await Redb.Context.ExecuteAsync(
$"DELETE FROM _values WHERE _id_object IN (SELECT _id FROM _objects WHERE _id_scheme = {scheme.Id})");
await Redb.Context.ExecuteAsync($"DELETE FROM _objects WHERE _id_scheme = {scheme.Id}");
return scheme.Id;
}
private async Task RootStructureIdAsync(long schemeId, string name) =>
(await Redb.Context.ExecuteScalarAsync(
$"SELECT _id FROM _structures WHERE _id_scheme = {schemeId} AND _name = '{name}' AND _id_parent IS NULL"))!.Value;
/// The stored string of a root field, read from the row itself (no cache in between).
private Task StoredStringAsync(long objectId, long structureId) =>
Redb.Context.ExecuteScalarAsync(
$"SELECT _String FROM _values WHERE _id_object = {objectId} AND _id_structure = {structureId}");
private async Task SaveEditProbeAsync(string? status, string? phone)
{
var obj = new RedbObject
{
name = "migration-edit-probe",
Props = new MigrationEditProbeProps { Status = status, Phone = phone }
};
obj.id = await Redb.SaveAsync(obj);
return obj.id;
}
private async Task SaveUniqueProbeAsync(long quantity, double price, double totalPrice)
{
var obj = new RedbObject
{
name = $"migration-unique-probe-{quantity}x{price}",
Props = new MigrationUniqueProbeProps { Quantity = quantity, Price = price, TotalPrice = totalPrice }
};
obj.id = await Redb.SaveAsync(obj);
return obj.id;
}
[Fact]
public async Task Migrate_DefaultValue_FillsTheStoredRowsWithoutAValue()
{
var schemeId = await ResetSchemeAsync();
var empty = await SaveEditProbeAsync(status: "Pending", phone: null);
var kept = await SaveEditProbeAsync(status: "Closed", phone: null);
var status = await RootStructureIdAsync(schemeId, nameof(MigrationEditProbeProps.Status));
// A stored row without a value: what a SQL-side writer or a field that stores nulls leaves behind.
await Redb.Context.ExecuteAsync($"UPDATE _values SET _String = NULL WHERE _id_object = {empty} AND _id_structure = {status}");
var results = await Redb.MigrateAsync(_dialect);
results.Should().OnlyContain(r => r.Success, "a failing migration reports Success=false with Error set: {0}",
string.Join(" | ", results.Select(r => r.Error)));
(await StoredStringAsync(empty, status)).Should().Be("Active");
(await StoredStringAsync(kept, status)).Should().Be("Closed", "DefaultValue fills only rows that hold no value");
}
[Fact]
public async Task Migrate_DefaultValue_OfABool_FillsTheStoredRowsWithoutAValue()
{
var schemeId = await ResetSchemeAsync();
var empty = await SaveEditProbeAsync(status: "Pending", phone: null);
var enabled = await RootStructureIdAsync(schemeId, nameof(MigrationEditProbeProps.Enabled));
(await Redb.Context.ExecuteAsync($"UPDATE _values SET _Boolean = NULL WHERE _id_object = {empty} AND _id_structure = {enabled}"))
.Should().Be(1, "the save stored a row for Enabled");
var results = await Redb.MigrateAsync(_dialect);
results.Should().OnlyContain(r => r.Success, "a failing migration reports Success=false with Error set: {0}",
string.Join(" | ", results.Select(r => r.Error)));
(await Redb.Context.ExecuteScalarAsync(
$"SELECT _Boolean FROM _values WHERE _id_object = {empty} AND _id_structure = {enabled}"))
.Should().BeTrue();
}
[Fact]
public async Task Migrate_DefaultValue_OfADateTimeAndADateTimeOffset_ReadsBackThroughTheApi()
{
var schemeId = await ResetSchemeAsync();
var id = await Redb.SaveAsync(new RedbObject
{
name = "migration-date-probe",
Props = new MigrationEditProbeProps
{
Due = new DateTime(2020, 1, 2, 3, 4, 5, DateTimeKind.Utc),
Seen = new DateTimeOffset(2020, 1, 2, 3, 4, 5, TimeSpan.Zero),
}
});
foreach (var field in new[] { nameof(MigrationEditProbeProps.Due), nameof(MigrationEditProbeProps.Seen) })
{
var structure = await RootStructureIdAsync(schemeId, field);
(await Redb.Context.ExecuteAsync(
$"UPDATE _values SET _DateTimeOffset = NULL WHERE _id_object = {id} AND _id_structure = {structure}"))
.Should().Be(1, "the save stored a row for {0}", field);
}
var results = await Redb.MigrateAsync(_dialect);
results.Should().OnlyContain(r => r.Success, "a failing migration reports Success=false with Error set: {0}",
string.Join(" | ", results.Select(r => r.Error)));
var loaded = await Redb.LoadAsync(id, depth: 1);
loaded.Props.Due.Should().NotBeNull();
loaded.Props.Due!.Value.ToUniversalTime().Should().Be(MigrationDateDefaultValueMigration.DueDefault);
loaded.Props.Seen.Should().NotBeNull();
loaded.Props.Seen!.Value.UtcDateTime.Should().Be(MigrationDateDefaultValueMigration.SeenDefault.UtcDateTime);
// A filter compares the stored value as the engine stores dates: a value written in another form is not found.
var due = MigrationDateDefaultValueMigration.DueDefault;
var seen = MigrationDateDefaultValueMigration.SeenDefault;
(await Redb.Query().Where(p => p.Due == due).CountAsync())
.Should().Be(1, "the filled DateTime is found by an equality filter");
(await Redb.Query().Where(p => p.Seen == seen).CountAsync())
.Should().Be(1, "the filled DateTimeOffset is found by an equality filter");
(await Redb.Query().Where(p => p.Due < due.AddDays(1)).CountAsync())
.Should().Be(1, "the filled DateTime orders below a later date");
}
[Fact]
public async Task Migrate_Transform_RewritesTheFieldInPlace()
{
var schemeId = await ResetSchemeAsync();
var first = await SaveEditProbeAsync(status: null, phone: "555-01-02");
var second = await SaveEditProbeAsync(status: null, phone: "777");
var phone = await RootStructureIdAsync(schemeId, nameof(MigrationEditProbeProps.Phone));
var results = await Redb.MigrateAsync(_dialect);
results.Should().OnlyContain(r => r.Success, "a failing migration reports Success=false with Error set: {0}",
string.Join(" | ", results.Select(r => r.Error)));
(await StoredStringAsync(first, phone)).Should().Be("5550102");
(await StoredStringAsync(second, phone)).Should().Be("777");
}
[Fact]
public async Task Migrate_ComputedFrom_OnAUniqueField_LeavesNoKeyOfTheOldValue()
{
await ResetSchemeAsync();
var migrated = await SaveUniqueProbeAsync(quantity: 3, price: 10.5, totalPrice: 0);
var results = await Redb.MigrateAsync(_dialect);
results.Should().OnlyContain(r => r.Success, "a failing migration reports Success=false with Error set: {0}",
string.Join(" | ", results.Select(r => r.Error)));
// The migrated object no longer holds 0: another object may take it.
var act = () => SaveUniqueProbeAsync(quantity: 1, price: 1, totalPrice: 0);
await act.Should().NotThrowAsync("the key of the value the migration replaced must not stay behind");
// The new value gets its key back by the recomputation the sync runs for keyless rows.
var report = await Redb.RecomputeUniqueAsync(nameof(MigrationUniqueProbeProps.TotalPrice));
report.HasDuplicates.Should().BeFalse();
var taken = () => SaveUniqueProbeAsync(quantity: 2, price: 2, totalPrice: 31.5);
await taken.Should().ThrowAsync($"object {migrated} holds 31.5 after the recomputation");
}
// ===== Literals: every kind of value the migration compiler writes into its SQL =====
public static TheoryData LiteralKinds => new()
{
{ nameof(MigrationLiteralProbeProps.Text), null },
{ nameof(MigrationLiteralProbeProps.Real), null },
{ nameof(MigrationLiteralProbeProps.Real), "sv-SE" },
{ nameof(MigrationLiteralProbeProps.Money), null },
{ nameof(MigrationLiteralProbeProps.Money), "sv-SE" },
{ nameof(MigrationLiteralProbeProps.Count), null },
{ nameof(MigrationLiteralProbeProps.Count), "sv-SE" },
{ nameof(MigrationLiteralProbeProps.Key), null },
{ nameof(MigrationLiteralProbeProps.At), null },
{ nameof(MigrationLiteralProbeProps.Seen), null },
{ nameof(MigrationLiteralProbeProps.Day), null },
{ nameof(MigrationLiteralProbeProps.Clock), null },
{ nameof(MigrationLiteralProbeProps.Span), null },
{ nameof(MigrationLiteralProbeProps.Kind), null },
{ nameof(MigrationLiteralProbeProps.Blob), null },
};
[Theory]
[MemberData(nameof(LiteralKinds))]
public Task Migrate_DefaultValue_WritesTheValueAsASaveDoes(string kind, string? culture)
=> LiteralProbeAsync(kind, culture);
[Theory]
[MemberData(nameof(LiteralKinds))]
public Task Migrate_ComputedFrom_WritesAConstantAsASaveDoes(string kind, string? culture)
=> LiteralProbeAsync(kind, culture);
[Fact]
public async Task Migrate_DefaultValue_OfNull_LeavesTheRowsWithoutAValue()
{
await ResetSchemeAsync();
var empty = await SaveLiteralProbeAsync(nameof(MigrationLiteralProbeProps.Text), clear: true);
MigrationLiteralValues.Current.Value = "Null";
var results = await Redb.MigrateAsync(_dialect);
results.Should().OnlyContain(r => r.Success, "a failing migration reports Success=false with Error set: {0}",
string.Join(" | ", results.Select(r => r.Error)));
(await Redb.LoadAsync(empty, depth: 1)).Props.Text.Should().BeNull();
}
///
/// One object saved with the value (the reference: how a save stores it), one whose stored row was emptied by SQL.
/// After the migration the emptied one reads back the value through the API, and a filter on the value finds both.
///
private async Task LiteralProbeAsync(string kind, string? culture)
where TMigration : IRedbMigration, new()
{
var before = CultureInfo.CurrentCulture;
try
{
var schemeId = await ResetSchemeAsync();
await SaveLiteralProbeAsync(kind, clear: false);
var empty = await SaveLiteralProbeAsync(kind, clear: true);
if (culture != null)
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture);
MigrationLiteralValues.Current.Value = kind;
var results = await Redb.MigrateAsync(_dialect);
CultureInfo.CurrentCulture = before;
results.Should().OnlyContain(r => r.Success, "a failing migration reports Success=false with Error set: {0}",
string.Join(" | ", results.Select(r => r.Error)));
var loaded = (await Redb.LoadAsync(empty, depth: 1)).Props;
AssertLiteral(kind, loaded);
if (kind == nameof(MigrationLiteralProbeProps.Kind))
// The query parser takes no == on a nullable enum: the stored name is counted directly.
(await Redb.Context.ExecuteScalarAsync(
"SELECT COUNT(*) FROM _values WHERE _String = 'Second' AND _id_object IN " +
$"(SELECT _id FROM _objects WHERE _id_scheme = {schemeId})"))
.Should().Be(2, "the filled enum is stored by name, as the saved one");
else if (kind != nameof(MigrationLiteralProbeProps.Blob))
(await Redb.Query().Where(LiteralFilter(kind)).CountAsync())
.Should().Be(2, "a filter on the value finds the saved object and the filled one");
}
finally
{
CultureInfo.CurrentCulture = before;
MigrationLiteralValues.Current.Value = null;
}
}
private async Task SaveLiteralProbeAsync(string kind, bool clear)
{
var props = new MigrationLiteralProbeProps();
switch (kind)
{
case nameof(MigrationLiteralProbeProps.Text): props.Text = MigrationLiteralValues.Text; break;
case nameof(MigrationLiteralProbeProps.Real): props.Real = MigrationLiteralValues.Real; break;
case nameof(MigrationLiteralProbeProps.Money): props.Money = MigrationLiteralValues.Money; break;
case nameof(MigrationLiteralProbeProps.Count): props.Count = MigrationLiteralValues.Count; break;
case nameof(MigrationLiteralProbeProps.Key): props.Key = MigrationLiteralValues.Key; break;
case nameof(MigrationLiteralProbeProps.At): props.At = MigrationLiteralValues.At; break;
case nameof(MigrationLiteralProbeProps.Seen): props.Seen = MigrationLiteralValues.Seen; break;
case nameof(MigrationLiteralProbeProps.Day): props.Day = MigrationLiteralValues.Day; break;
case nameof(MigrationLiteralProbeProps.Clock): props.Clock = MigrationLiteralValues.Clock; break;
case nameof(MigrationLiteralProbeProps.Span): props.Span = MigrationLiteralValues.Span; break;
case nameof(MigrationLiteralProbeProps.Kind): props.Kind = MigrationLiteralValues.Kind; break;
case nameof(MigrationLiteralProbeProps.Blob): props.Blob = MigrationLiteralValues.Blob; break;
}
var id = await Redb.SaveAsync(new RedbObject { name = $"literal-{kind}", Props = props });
if (clear)
(await Redb.Context.ExecuteAsync(
"UPDATE _values SET _String = NULL, _Long = NULL, _Guid = NULL, _Double = NULL, _DateTimeOffset = NULL, " +
$"_ByteArray = NULL, _Numeric = NULL WHERE _id_object = {id}"))
.Should().Be(1, "the save stored one row for {0}", kind);
return id;
}
private static void AssertLiteral(string kind, MigrationLiteralProbeProps p)
{
switch (kind)
{
case nameof(MigrationLiteralProbeProps.Text): p.Text.Should().Be(MigrationLiteralValues.Text); break;
case nameof(MigrationLiteralProbeProps.Real): p.Real.Should().Be(MigrationLiteralValues.Real); break;
case nameof(MigrationLiteralProbeProps.Money): p.Money.Should().Be(MigrationLiteralValues.Money); break;
case nameof(MigrationLiteralProbeProps.Count): p.Count.Should().Be(MigrationLiteralValues.Count); break;
case nameof(MigrationLiteralProbeProps.Key): p.Key.Should().Be(MigrationLiteralValues.Key); break;
case nameof(MigrationLiteralProbeProps.At): p.At!.Value.ToUniversalTime().Should().Be(MigrationLiteralValues.At); break;
case nameof(MigrationLiteralProbeProps.Seen): p.Seen!.Value.UtcDateTime.Should().Be(MigrationLiteralValues.Seen.UtcDateTime); break;
case nameof(MigrationLiteralProbeProps.Day): p.Day.Should().Be(MigrationLiteralValues.Day); break;
case nameof(MigrationLiteralProbeProps.Clock): p.Clock.Should().Be(MigrationLiteralValues.Clock); break;
case nameof(MigrationLiteralProbeProps.Span): p.Span.Should().Be(MigrationLiteralValues.Span); break;
case nameof(MigrationLiteralProbeProps.Kind): p.Kind.Should().Be(MigrationLiteralValues.Kind); break;
case nameof(MigrationLiteralProbeProps.Blob): p.Blob.Should().Equal(MigrationLiteralValues.Blob); break;
}
}
private static System.Linq.Expressions.Expression> LiteralFilter(string kind)
{
var key = MigrationLiteralValues.Key;
var at = MigrationLiteralValues.At;
var seen = MigrationLiteralValues.Seen;
var day = MigrationLiteralValues.Day;
var clock = MigrationLiteralValues.Clock;
var span = MigrationLiteralValues.Span;
return kind switch
{
nameof(MigrationLiteralProbeProps.Text) => p => p.Text == MigrationLiteralValues.Text,
nameof(MigrationLiteralProbeProps.Real) => p => p.Real == MigrationLiteralValues.Real,
nameof(MigrationLiteralProbeProps.Money) => p => p.Money == MigrationLiteralValues.Money,
nameof(MigrationLiteralProbeProps.Count) => p => p.Count == MigrationLiteralValues.Count,
nameof(MigrationLiteralProbeProps.Key) => p => p.Key == key,
nameof(MigrationLiteralProbeProps.At) => p => p.At == at,
nameof(MigrationLiteralProbeProps.Seen) => p => p.Seen == seen,
nameof(MigrationLiteralProbeProps.Day) => p => p.Day == day,
nameof(MigrationLiteralProbeProps.Clock) => p => p.Clock == clock,
nameof(MigrationLiteralProbeProps.Span) => p => p.Span == span,
_ => throw new ArgumentOutOfRangeException(nameof(kind), kind, null),
};
}
}