Path: redb/redb.Tests.Integration/Tests/Base/SchemeNamingTestsBase.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/SchemeNamingTestsBase.cs
----
using redb.Core;
using redb.Core.Exceptions;
using redb.Core.Models.Entities;
using redb.Core.Utils;
using redb.Tests.Integration.Models;
namespace redb.Tests.Integration.Tests.Base;
///
/// Scenarios A–U for explicit scheme names ([RedbScheme(Name = "...")]), scheme alias
/// synchronisation, and the multi-node scheme creation race.
///
/// Every test drops the schemes it touches first, so the suite is repeatable and order-independent —
/// which matters because Free and Pro fixtures share a database on every provider.
///
///
public abstract class SchemeNamingTestsBase
{
protected readonly IRedbService Redb;
protected SchemeNamingTestsBase(IRedbService redb) => Redb = redb;
// ============================================================
// === helpers ===
// ============================================================
/// Removes schemes by name (structures first — they are FK-bound) and clears the cache.
private async Task DropSchemesAsync(params string[] names)
{
foreach (var name in names)
{
await Redb.Context.ExecuteAsync(
$"DELETE FROM _structures WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{name}')");
await Redb.Context.ExecuteAsync($"DELETE FROM _schemes WHERE _name = '{name}'");
}
// Raw SQL is invisible to the metadata cache; without this a later lookup would answer from a
// scheme that no longer exists.
Redb.Cache.Clear();
}
private Task SchemeIdAsync(string name) =>
Redb.Context.ExecuteScalarAsync($"SELECT _id FROM _schemes WHERE _name = '{name}'");
private Task SchemeAliasAsync(string name) =>
Redb.Context.ExecuteScalarAsync($"SELECT _alias FROM _schemes WHERE _name = '{name}'");
private Task SchemeNameSpaceAsync(string name) =>
Redb.Context.ExecuteScalarAsync($"SELECT _name_space FROM _schemes WHERE _name = '{name}'");
/// Creates a scheme row directly, bypassing the library — the "other node" in race tests.
private async Task InsertSchemeRawAsync(string name, long type = RedbTypeIds.Class, string? nameSpace = null)
{
var id = await Redb.Context.NextObjectIdAsync();
var nsColumn = nameSpace != null ? ", _name_space" : "";
var nsValue = nameSpace != null ? $", '{nameSpace}'" : "";
await Redb.Context.ExecuteAsync(
$"INSERT INTO _schemes (_id, _name, _type{nsColumn}) VALUES ({id}, '{name}', {type}{nsValue})");
Redb.Cache.Clear();
return id;
}
private static string FullNameOf() => typeof(T).FullName!;
// ============================================================
// === A, B — no explicit name: legacy behaviour is untouched ===
// ============================================================
[Fact]
public async Task A_NoExplicitName_SchemeLivesByFullName()
{
var fullName = FullNameOf();
await DropSchemesAsync(fullName, nameof(NamingByTypeProps));
var scheme = await Redb.EnsureSchemeFromTypeAsync();
scheme.Name.Should().Be(fullName);
(await SchemeIdAsync(fullName)).Should().NotBeNull();
(await SchemeIdAsync(nameof(NamingByTypeProps))).Should().BeNull();
}
[Fact]
public async Task B_NoExplicitName_MigratesFromShortName()
{
var fullName = FullNameOf();
var shortName = nameof(NamingByTypeProps);
await DropSchemesAsync(fullName, shortName);
var legacyId = await InsertSchemeRawAsync(shortName);
var scheme = await Redb.EnsureSchemeFromTypeAsync();
scheme.Name.Should().Be(fullName);
scheme.Id.Should().Be(legacyId, "renaming must preserve the id so objects stay attached");
(await SchemeIdAsync(shortName)).Should().BeNull();
(await SchemeNameSpaceAsync(fullName)).Should().Be(typeof(NamingByTypeProps).Namespace,
"К7: adoption via the short name stamps the owner namespace");
}
// ============================================================
// === C, D, E — the three-step chain ===
// ============================================================
[Fact]
public async Task C_ExplicitName_CreatedOnCleanDatabase()
{
await DropSchemesAsync("naming.pinned", FullNameOf(), nameof(NamingPinnedProps));
var scheme = await Redb.EnsureSchemeFromTypeAsync();
scheme.Name.Should().Be("naming.pinned");
(await SchemeIdAsync(FullNameOf())).Should().BeNull("FullName must not be used at all");
}
[Fact]
public async Task D_ExplicitName_RenamesSchemeFoundByFullName()
{
var fullName = FullNameOf();
await DropSchemesAsync("naming.pinned", fullName, nameof(NamingPinnedProps));
var originalId = await InsertSchemeRawAsync(fullName);
var scheme = await Redb.EnsureSchemeFromTypeAsync();
scheme.Name.Should().Be("naming.pinned");
scheme.Id.Should().Be(originalId, "the rename is an UPDATE of _name, not a new scheme");
(await SchemeIdAsync(fullName)).Should().BeNull();
}
[Fact]
public async Task E_ExplicitName_RenamesSchemeFoundByShortName()
{
var shortName = nameof(NamingPinnedProps);
await DropSchemesAsync("naming.pinned", FullNameOf(), shortName);
var originalId = await InsertSchemeRawAsync(shortName);
var scheme = await Redb.EnsureSchemeFromTypeAsync();
scheme.Name.Should().Be("naming.pinned");
scheme.Id.Should().Be(originalId, "the third link of the chain must not orphan pre-FullName databases");
(await SchemeIdAsync(shortName)).Should().BeNull();
}
// ============================================================
// === F, G, H — failing loudly ===
// ============================================================
[Fact]
public async Task F_SplitBrain_TargetAndPreviousNameBothExist_Throws()
{
var fullName = FullNameOf();
await DropSchemesAsync("naming.split", fullName, nameof(NamingSplitProps));
// The rename already happened, and then an older binary re-created the old scheme.
await InsertSchemeRawAsync("naming.split");
await InsertSchemeRawAsync(fullName);
var act = async () => await Redb.EnsureSchemeFromTypeAsync();
await act.Should().ThrowAsync();
// Both rows survive: the operator has to merge them, the library must not pick one silently.
(await SchemeIdAsync("naming.split")).Should().NotBeNull();
(await SchemeIdAsync(fullName)).Should().NotBeNull();
await DropSchemesAsync("naming.split", fullName);
}
// Scenarios G (two types claiming one name) and H (invalid explicit name) are NOT integration
// tests: they would require a type with a bad or duplicate name to exist in this assembly, and
// InitializeAsync auto-syncs every [RedbScheme] type it can see and rethrows — so such a type
// breaks fixture start-up for every other test here. That is the intended product behaviour.
// The rules themselves are covered by Tests/Unit/SchemeNameValidatorTests.
// ============================================================
// === I, J — the database-level backstop ===
// ============================================================
[Theory]
// Character-set rule — a single GLOB/LIKE test in every dialect.
[InlineData("Raw Invalid Name")]
[InlineData("Именование сырьём")]
// Structural rules.
[InlineData("raw..double")]
[InlineData("raw.trailing.")]
[InlineData("9raw")]
// Reserved-word rule. This is the one that forced a recursive CTE in SQLite and STRING_SPLIT in
// MSSql — it is the only case that actually splits the name into parts, so without it the
// per-part machinery would never run and could be broken without anyone noticing.
[InlineData("raw.class")]
[InlineData("raw+static")]
public async Task I_RawInsertOfInvalidName_RejectedByTrigger(string invalid)
{
await DropSchemesAsync(invalid);
var act = async () => await InsertSchemeRawAsync(invalid);
await act.Should().ThrowAsync("the trigger is the backstop for writes that bypass the library");
(await SchemeIdAsync(invalid)).Should().BeNull();
}
[Fact]
public async Task J_SystemPrefixedName_BypassesValidation()
{
const string systemName = "@@naming_probe";
await DropSchemesAsync(systemName);
var id = await InsertSchemeRawAsync(systemName);
id.Should().BeGreaterThan(0);
(await SchemeIdAsync(systemName)).Should().Be(id);
await DropSchemesAsync(systemName);
}
// ============================================================
// === K, L — caches and RTTI survive the rename ===
// ============================================================
[Fact]
public async Task K_AfterRename_LookupsUseTheNewNameOnly()
{
var fullName = FullNameOf();
await DropSchemesAsync("naming.pinned", fullName, nameof(NamingPinnedProps));
await InsertSchemeRawAsync(fullName);
var scheme = await Redb.EnsureSchemeFromTypeAsync();
(await Redb.GetSchemeByNameAsync("naming.pinned"))!.Id.Should().Be(scheme.Id);
(await Redb.GetSchemeByNameAsync(fullName)).Should().BeNull("the old name must not resolve to a stale scheme");
(await Redb.GetSchemeByTypeAsync())!.Id.Should().Be(scheme.Id);
Redb.GetSchemeNameForType().Should().Be("naming.pinned");
}
[Fact]
public async Task L_AfterRename_ObjectsRoundTrip()
{
await DropSchemesAsync("naming.pinned", FullNameOf(), nameof(NamingPinnedProps));
await Redb.SyncSchemeAsync();
var obj = new RedbObject
{
name = "naming-roundtrip",
Props = new NamingPinnedProps { Title = "after rename" }
};
obj.id = await Redb.SaveAsync(obj);
var loaded = await Redb.LoadAsync(obj.id);
loaded.Should().NotBeNull();
loaded!.Props.Title.Should().Be("after rename");
}
// ============================================================
// === M, N — name plus alias, and idempotency ===
// ============================================================
[Fact]
public async Task M_ExplicitNameAndAlias_BothPersisted()
{
await DropSchemesAsync("naming.with_alias", FullNameOf(), nameof(NamingWithAliasProps));
var scheme = await Redb.EnsureSchemeFromTypeAsync();
scheme.Name.Should().Be("naming.with_alias");
(await SchemeAliasAsync("naming.with_alias")).Should().Be("Именование: имя и алиас");
}
[Fact]
public async Task N_RepeatedSync_IsIdempotent()
{
await DropSchemesAsync("naming.pinned", FullNameOf(), nameof(NamingPinnedProps));
var first = await Redb.EnsureSchemeFromTypeAsync();
var second = await Redb.EnsureSchemeFromTypeAsync();
var third = await Redb.EnsureSchemeFromTypeAsync();
second.Id.Should().Be(first.Id);
third.Id.Should().Be(first.Id);
second.Name.Should().Be("naming.pinned");
}
// ============================================================
// === O, P, R — the alias follows the attribute ===
// ============================================================
[Fact]
public async Task O_AliasChangedInDatabase_IsRestoredFromAttribute()
{
var fullName = FullNameOf();
await DropSchemesAsync(fullName, nameof(NamingAliasProps));
var scheme = await Redb.EnsureSchemeFromTypeAsync();
(await SchemeAliasAsync(fullName)).Should().Be("Именование: алиас исходный");
// R: someone edits the alias by hand.
await Redb.Context.ExecuteAsync($"UPDATE _schemes SET _alias = 'правка руками' WHERE _id = {scheme.Id}");
Redb.Cache.Clear();
await Redb.EnsureSchemeFromTypeAsync();
(await SchemeAliasAsync(fullName)).Should().Be("Именование: алиас исходный",
"the attribute is the source of truth, exactly as it already is for structure aliases");
}
[Fact]
public async Task P_TypeWithoutAlias_ResetsAliasToNull()
{
await DropSchemesAsync("naming.pinned", FullNameOf(), nameof(NamingPinnedProps));
var scheme = await Redb.EnsureSchemeFromTypeAsync();
await Redb.Context.ExecuteAsync($"UPDATE _schemes SET _alias = 'лишний алиас' WHERE _id = {scheme.Id}");
Redb.Cache.Clear();
await Redb.EnsureSchemeFromTypeAsync();
(await SchemeAliasAsync("naming.pinned")).Should().BeNull(
"a type that declares no alias must clear the column, not leave a ghost");
}
[Fact]
public async Task Q_AliasStableAcrossRepeatedSyncs()
{
var fullName = FullNameOf();
await DropSchemesAsync(fullName, nameof(NamingAliasProps));
await Redb.EnsureSchemeFromTypeAsync();
await Redb.EnsureSchemeFromTypeAsync();
await Redb.EnsureSchemeFromTypeAsync();
(await SchemeAliasAsync(fullName)).Should().Be("Именование: алиас исходный");
}
// ============================================================
// === S, T, U — the multi-node creation race ===
// ============================================================
[Fact]
public async Task S_LosingTheCreationRace_AdoptsTheWinnersScheme()
{
await DropSchemesAsync("naming.race", FullNameOf(), nameof(NamingRaceProps));
// Another node got there first: the row exists, and our lookups have already missed it.
var winnerId = await InsertSchemeRawAsync("naming.race");
var scheme = await Redb.EnsureSchemeFromTypeAsync();
scheme.Id.Should().Be(winnerId, "the loser must adopt the existing scheme, not fail on UNIQUE(_name)");
(await Redb.Context.ExecuteScalarAsync(
"SELECT COUNT(*) FROM _schemes WHERE _name = 'naming.race'")).Should().Be(1);
}
[Fact]
public async Task T_LosingTheCreationRace_InsideTransaction_TransactionStillCommits()
{
await DropSchemesAsync("naming.race", FullNameOf(), nameof(NamingRaceProps));
var winnerId = await InsertSchemeRawAsync("naming.race");
// The point of the test: on PostgreSQL a raised unique violation would poison the transaction
// and every following statement would fail with 25P02. Suppressing the conflict in SQL instead
// of catching it is what keeps this commit possible.
long adoptedId = 0;
var act = async () => await Redb.Context.ExecuteAtomicAsync(async () =>
{
var scheme = await Redb.EnsureSchemeFromTypeAsync();
adoptedId = scheme.Id;
});
await act.Should().NotThrowAsync();
adoptedId.Should().Be(winnerId);
}
[Fact]
public async Task U_ObjectSchemePath_HasTheSameProtection()
{
const string objectSchemeName = "naming_object_race";
await DropSchemesAsync(objectSchemeName);
var winnerId = await InsertSchemeRawAsync(objectSchemeName, RedbTypeIds.Object);
var scheme = await Redb.EnsureObjectSchemeAsync(objectSchemeName);
scheme.Id.Should().Be(winnerId, "the untyped path must not be a second door into the same bug");
(await Redb.Context.ExecuteScalarAsync(
$"SELECT COUNT(*) FROM _schemes WHERE _name = '{objectSchemeName}'")).Should().Be(1);
await DropSchemesAsync(objectSchemeName);
}
// ============================================================
// === V, W, X — namespace as the ownership mark (V4, К7) ===
// ============================================================
[Fact]
public async Task V_NameSpace_WrittenOnCreate_AndRestoredFromCode()
{
var fullName = FullNameOf();
await DropSchemesAsync(fullName, nameof(NamingByTypeProps));
await Redb.EnsureSchemeFromTypeAsync();
(await SchemeNameSpaceAsync(fullName)).Should().Be(typeof(NamingByTypeProps).Namespace);
// A cleared owner (a pre-namespace database, or a deliberate hand-off) is re-stamped.
await Redb.Context.ExecuteAsync($"UPDATE _schemes SET _name_space = NULL WHERE _name = '{fullName}'");
Redb.Cache.Clear();
await Redb.EnsureSchemeFromTypeAsync();
(await SchemeNameSpaceAsync(fullName)).Should().Be(typeof(NamingByTypeProps).Namespace);
// A different owner is never overwritten, on any path: a scheme has one owner (К7, owner
// decision 2026-09-01) - the typed stop names the way out instead.
await Redb.Context.ExecuteAsync($"UPDATE _schemes SET _name_space = 'Hacked.Ns' WHERE _name = '{fullName}'");
Redb.Cache.Clear();
var act = async () => await Redb.EnsureSchemeFromTypeAsync();
var ex = (await act.Should().ThrowAsync()).Which;
ex.SchemeNameSpace.Should().Be("Hacked.Ns");
ex.Message.Should().Contain("_name_space", "the message tells the operator what to do");
(await SchemeNameSpaceAsync(fullName)).Should().Be("Hacked.Ns", "the row is left as it is");
}
[Fact]
public async Task W_ShortNameAdoption_MatchingNamespace_Renames()
{
var fullName = FullNameOf();
var shortName = nameof(NamingByTypeProps);
await DropSchemesAsync(fullName, shortName);
var legacyId = await InsertSchemeRawAsync(shortName, nameSpace: typeof(NamingByTypeProps).Namespace);
var scheme = await Redb.EnsureSchemeFromTypeAsync();
scheme.Id.Should().Be(legacyId, "a matching namespace proves ownership — adoption proceeds");
scheme.Name.Should().Be(fullName);
(await SchemeNameSpaceAsync(fullName)).Should().Be(typeof(NamingByTypeProps).Namespace);
}
[Fact]
public async Task X_ShortNameAdoption_ForeignNamespace_Throws()
{
var fullName = FullNameOf();
var shortName = nameof(NamingByTypeProps);
await DropSchemesAsync(fullName, shortName);
var foreignId = await InsertSchemeRawAsync(shortName, nameSpace: "Some.Other.Project");
var act = async () => await Redb.EnsureSchemeFromTypeAsync();
await act.Should().ThrowAsync(
"a short name proves nothing — the scheme belongs to another project");
// Untouched: still under the short name, same id, same owner.
(await SchemeIdAsync(shortName)).Should().Be(foreignId);
(await SchemeNameSpaceAsync(shortName)).Should().Be("Some.Other.Project");
await DropSchemesAsync(shortName);
}
[Fact]
public async Task Y_ExplicitNameAdoption_ForeignNamespace_Throws()
{
const string pinned = "naming.pinned";
await DropSchemesAsync(pinned, FullNameOf(), nameof(NamingPinnedProps));
var foreignId = await InsertSchemeRawAsync(pinned, nameSpace: "Some.Other.Project");
try
{
var act = async () => await Redb.EnsureSchemeFromTypeAsync();
await act.Should().ThrowAsync(
"К7: a scheme has one owner - an explicit name from another project must not take it over");
(await SchemeIdAsync(pinned)).Should().Be(foreignId);
(await SchemeNameSpaceAsync(pinned)).Should().Be("Some.Other.Project", "the row stays untouched");
}
finally
{
await DropSchemesAsync(pinned);
}
}
}