Path: redb/redb.Core/Providers/Base/SchemeSyncProviderBase.Rename.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.Core/Providers/Base/SchemeSyncProviderBase.Rename.cs
----
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using redb.Core.Attributes;
using redb.Core.Caching;
using redb.Core.Exceptions;
using redb.Core.Models.Entities;
using Microsoft.Extensions.Logging;
namespace redb.Core.Providers.Base;
///
/// Rename side of the scheme sync: on properties.
///
/// A property whose name is not stored but whose previous name is takes the stored structure: one UPDATE of the name
/// through the dialect, the id and every value stay. The previous names are kept in _structures._renamed_from
/// (a JSON array, oldest first), so that a class that predates the rename stops at its sync instead of adding the old
/// name again and, under the strict sync, deleting the renamed structure with its values.
///
///
/// The names a rename changes reach everything derived from them through the steps of the sync that follow it: the
/// scheme hash ( hashes the names) is recomputed and the scheme and structure
/// tree caches are dropped when it moves, and the metadata cache table is rebuilt by the writing pass.
///
///
public abstract partial class SchemeSyncProviderBase
{
///
/// Checks one level of a class (the root of the scheme, or the class of a nested property) against the previous
/// names stored at that level: a stored structure that the class does not claim, by its name or by a
/// , while the class declares one of its previous names, means the class is older
/// than the rename. Runs before anything is written at the level.
///
private static void CheckRenamedAway(string schemeName, Type type, IReadOnlyList properties, long? parentId,
List existingStructures)
{
var declared = properties.Select(p => p.Name).ToHashSet(StringComparer.Ordinal);
CheckOneStepSwap(type, properties);
var claimed = new HashSet(declared, StringComparer.Ordinal);
foreach (var property in properties)
foreach (var rename in property.GetCustomAttributes(false))
claimed.Add(rename.OldName);
var level = existingStructures.Where(s => s.IdParent == parentId).ToList();
foreach (var stored in level)
{
if (stored.RenamedFrom == null || claimed.Contains(stored.Name))
continue;
var previous = ReadRenamedFrom(stored);
var hit = previous.LastOrDefault(declared.Contains);
if (hit != null)
throw RedbRenameConflictException.RenamedAway(schemeName, $"{type.Name}.{hit}", stored.Name, stored.Id);
}
foreach (var property in properties)
{
var name = property.Name;
var path = $"{type.Name}.{name}";
var chain = DeclaredRenames(property);
var current = level.FirstOrDefault(s => s.Name == name);
var oldNames = chain.Where(n => n != name).Distinct(StringComparer.Ordinal).ToList();
var ownOldNames = oldNames.Where(n => !declared.Contains(n)).ToList();
// A previous name another property of the class carries again (a freed name taken by a new property) is
// read only once the rename is applied: while the database stores such a name and neither the current name
// nor a previous name no other property carries, the stored structure could belong to either property.
if (current == null && !level.Any(s => ownOldNames.Contains(s.Name)))
{
var reused = oldNames.FirstOrDefault(n => declared.Contains(n) && level.Any(s => s.Name == n));
if (reused != null)
throw new InvalidOperationException(
$"[RedbRename(\"{reused}\")] on '{path}': the class '{type.FullName ?? type.Name}' also declares a " +
$"property '{reused}', and the database stores '{reused}' but not '{name}'. The stored structure " +
$"could belong to either property. Apply the rename with a class that does not declare " +
$"'{reused}' again, then add the new property.");
}
// The first name of the property is part of the hash canon (RedbHash.HashSortKey): the history the database
// keeps must start with the first [RedbRename] the class declares, or the stored hashes were computed in
// another order than the class computes them now.
var matched = current ?? level.Where(s => ownOldNames.Contains(s.Name)).OrderBy(s => s.Id).FirstOrDefault();
if (matched == null)
continue;
var history = ReadRenamedFrom(matched);
if (history.Count > 0 && (chain.Count == 0 || chain[0] != history[0]))
throw RedbRenameConflictException.FirstNameMismatch(schemeName, path, matched.Id, history,
chain.Count == 0 ? null : chain[0]);
}
}
///
/// Refuses two properties of one class level that swap names in one step: the last
/// of each (the attribute declared last; the attributes are read in declaration order, the order the first-name
/// check verifies against the stored history) names the current name of the other. Each of the two renames needs
/// its target name free, and the target is the other property's name until that one is renamed, so the pair can
/// only mean both renames at once; the sync would find both current names stored and rename nothing, leaving the
/// values under the names they had. A swap through a temporary name leaves other last names and passes. Read from
/// the class alone.
///
private static void CheckOneStepSwap(Type type, IReadOnlyList properties)
{
var lastNames = new Dictionary(StringComparer.Ordinal);
foreach (var property in properties)
{
var last = DeclaredRenames(property).LastOrDefault();
if (last != null && last != property.Name)
lastNames[property.Name] = last;
}
foreach (var (name, last) in lastNames)
{
if (string.CompareOrdinal(name, last) > 0 || !lastNames.TryGetValue(last, out var back) || back != name)
continue;
throw new InvalidOperationException(
$"[RedbRename(\"{last}\")] on '{type.Name}.{name}' and [RedbRename(\"{name}\")] on '{type.Name}.{last}': " +
$"the class '{type.FullName ?? type.Name}' swaps the two names in one step, which the sync cannot apply. " +
$"Swap them through a temporary name, one deployment per rename: '{name}' to a temporary name, then " +
$"'{last}' to '{name}', then the temporary name to '{last}'.");
}
}
/// The names of the s of a property, in declaration order.
private static List DeclaredRenames(PropertyInfo property)
=> property.GetCustomAttributes(false).Select(a => a.OldName).ToList();
///
/// The stored structure of a property: under its name, or under one of its previous names, which is then renamed
/// in place. Null when the property is new.
///
private async Task MatchStructureAsync(string schemeName, Type type, PropertyInfo property,
IReadOnlyList properties, long? parentId, List existingStructures,
CancellationToken cancellationToken = default)
{
var name = property.Name;
var path = $"{type.Name}.{name}";
var current = existingStructures.FirstOrDefault(s => s.Name == name && s.IdParent == parentId);
var chain = DeclaredRenames(property);
// A previous name another property carries again belongs to that property once the rename is applied; the
// level check (CheckRenamedAway) has already refused the state in which it is not.
var oldNames = chain
.Where(n => n != name && properties.All(p => p.Name != n))
.Distinct(StringComparer.Ordinal)
.ToList();
if (oldNames.Count == 0)
return current;
var stored = existingStructures
.Where(s => s.IdParent == parentId && oldNames.Contains(s.Name))
.OrderBy(s => s.Id)
.ToList();
if (stored.Count == 0)
return current;
if (current != null)
throw RedbRenameConflictException.BothStored(schemeName, path, stored[0].Name, current.Id, stored[0].Id);
if (stored.Count > 1)
throw RedbRenameConflictException.SeveralStored(schemeName, path, stored.Select(s => (s.Name, s.Id)).ToList());
var renamed = stored[0];
var renamedFrom = StructureHistoryAfterRename(ReadRenamedFrom(renamed), chain, renamed.Name);
BeforeSchemeWrite();
await Context.ExecuteAsync(Sql.Structures_Rename(), new object[] { name, renamedFrom, renamed.Id }, cancellationToken);
Logger?.LogInformation(
"REDB schema sync: scheme '{SchemeName}': structure {StructureId} renamed from '{OldName}' to '{NewName}' ([RedbRename]).",
schemeName, renamed.Id, renamed.Name, name);
renamed.Name = name;
renamed.RenamedFrom = renamedFrom;
return renamed;
}
/// The previous names of a structure, oldest first; empty when it was never renamed.
private static List ReadRenamedFrom(RedbStructure structure)
=> ReadRenamedFrom(structure.RenamedFrom, $"_structures._renamed_from of structure {structure.Id} ('{structure.Name}')");
/// The previous names of a scheme, oldest first; empty when it was never renamed.
private static List ReadRenamedFrom(RedbScheme scheme)
=> ReadRenamedFrom(scheme.RenamedFrom, $"_schemes._renamed_from of scheme {scheme.Id} ('{scheme.Name}')");
private static List ReadRenamedFrom(string? json, string what)
{
if (string.IsNullOrEmpty(json))
return [];
try
{
return System.Text.Json.JsonSerializer.Deserialize>(json) ?? [];
}
catch (System.Text.Json.JsonException ex)
{
throw new InvalidOperationException(
$"{what} is not a JSON array of names: '{json}'. Correct or clear the column by hand.", ex);
}
}
///
/// The history of a structure after one more rename, oldest first. A structure renamed before keeps its history and
/// gets the name it is renamed from appended. A structure renamed for the first time gets the declared chain up to
/// that name: a database created with a class that already carried [RedbRename] has no history of the names before
/// it, and the first name of the chain is what the hash canon sorts by. The current name is never removed, so the
/// first entry stays the first name even when a property is renamed back.
///
private static string StructureHistoryAfterRename(List previous, List chain, string renamedFrom)
{
var list = previous.Count > 0
? new List(previous)
: chain.TakeWhile(n => n != renamedFrom).Distinct(StringComparer.Ordinal).ToList();
if (!list.Contains(renamedFrom))
list.Add(renamedFrom);
return System.Text.Json.JsonSerializer.Serialize(list);
}
/// The history after one more rename: the previous list with the name renamed from appended.
private static string AppendRenamedFrom(List previous, string renamedFrom, string newName)
{
var list = previous.Where(n => n != newName).ToList();
if (!list.Contains(renamedFrom))
list.Add(renamedFrom);
return System.Text.Json.JsonSerializer.Serialize(list);
}
///
/// The previous scheme names a class declares (), newest first: the
/// lookup tries the most recent name before older ones. Empty and repeated names and the target name are skipped.
///
private static List GetDeclaredPreviousSchemeNames(Type type, string targetName)
{
var declared = type.GetCustomAttribute()?.RenamedFrom;
if (declared == null || declared.Length == 0)
return [];
return declared
.Where(n => !string.IsNullOrWhiteSpace(n) && n != targetName)
.Distinct(StringComparer.Ordinal)
.Reverse()
.ToList();
}
///
/// Renames a scheme in place and records the name it had in _schemes._renamed_from. The id stays, so every
/// object and structure stays with it.
///
private async Task RenameSchemeAsync(RedbScheme scheme, string previousName, string targetName, Type type,
CancellationToken cancellationToken)
{
BeforeSchemeWrite();
Logger?.LogInformation(
"Renaming scheme '{OldName}' to '{NewName}' (ID: {SchemeId}, InTransaction: {InTx})",
previousName, targetName, scheme.Id, Context.CurrentTransaction != null);
var renamedFrom = AppendRenamedFrom(ReadRenamedFrom(scheme), previousName, targetName);
var rowsAffected = await Context.ExecuteAsync(Sql.Schemes_Rename(), new object[] { targetName, renamedFrom, scheme.Id },
cancellationToken);
if (rowsAffected == 0)
{
Logger?.LogWarning("Rename UPDATE affected 0 rows for scheme ID {SchemeId}. SQL: {Sql}",
scheme.Id, Sql.Schemes_Rename());
}
scheme.Name = targetName;
scheme.RenamedFrom = renamedFrom;
// Three keys: the id, the name it was found under, and the target name (in case a stale entry sits there). The
// process-global name -> Type index is refreshed immediately rather than waiting for the next assembly rescan.
Cache.InvalidateScheme(scheme.Id);
Cache.InvalidateScheme(previousName);
Cache.InvalidateScheme(targetName);
ClrSchemeTypeIndex.Register(targetName, type);
}
///
/// Before a scheme is created: a stored scheme whose previous names hold the name about to be created, while no class
/// of this application declares that scheme under its current name, means the class is older than the rename.
/// A class that does declare it is a new scheme taking a freed name, which is allowed.
///
private async Task CheckSchemeRenamedAwayAsync(Type type, string targetName, CancellationToken cancellationToken)
{
var renamed = await Context.QueryAsync(Sql.Schemes_SelectRenamed(), Array.Empty