Path: redb/redb.Core/Data/RootStructureKey.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/Data/RootStructureKey.cs
----
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using redb.Core.Models.Entities;
using redb.Core.Query;
using redb.Core.Utils;
namespace redb.Core.Data
{
///
/// The unique key of the root structures of a scheme: one field name once per scheme. The key of
/// _structures (_id_scheme, _name, _id_parent) lets a root field in twice on PostgreSQL and SQLite, where two
/// NULL parents are distinct, and nodes syncing one scheme at once used to do exactly that (SQL Server counts NULLs
/// as equal and refused it). The SQL is the dialect's (the "root structure key" group of );
/// this class decides.
///
///
/// A database written before the schema lock may hold such duplicates already, and the key cannot be built over
/// them. A duplicate nothing points to (no value, no child with a value, no structure overriding it, no migration
/// record) is removed with its subtree; one with values is left alone, and the key waits until the duplicates are
/// resolved by hand (UPGRADING.md, "Duplicate root structures"). Run under the schema lock, in one transaction.
///
///
public static class RootStructureKey
{
/// Name of the unique key, as the dialects create it.
public const string IndexName = "UX__structures__root";
///
/// Removes the empty root duplicates and builds the key when none with values remain. Called only for a dialect
/// whose is not null.
///
/// The context of the service; joins its transaction or opens one.
/// The dialect.
/// Whether _migrations exists; its rows point to structures.
/// Where removals are reported.
/// Cancellation.
/// True when the key exists afterwards.
public static async Task EnsureAsync(
IRedbContext context, ISqlDialect sql, bool hasMigrationsTable, ILogger? logger,
CancellationToken cancellationToken = default)
{
IRedbTransaction? own = context.IsInTransaction
? null
: await context.BeginTransactionAsync(cancellationToken: cancellationToken);
try
{
var created = await EnsureInTransactionAsync(context, sql, hasMigrationsTable, logger, cancellationToken);
if (own != null)
await own.CommitAsync();
return created;
}
catch (Exception failure)
{
if (own != null)
await RollbackAfterFailure.RollbackAsync(own, failure);
throw;
}
finally
{
if (own != null)
await own.DisposeAsync();
}
}
private static async Task EnsureInTransactionAsync(
IRedbContext context, ISqlDialect sql, bool hasMigrationsTable, ILogger? logger, CancellationToken cancellationToken)
{
var roots = await context.QueryAsync(
sql.Structures_SelectRootDuplicates(), Array.Empty