Path: redb/redb.Core/Utils/RedbHash.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/Utils/RedbHash.cs
----
using redb.Core.Models.Entities;
using redb.Core.Models.Contracts;
using redb.Core.Attributes;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Serialization;
namespace redb.Core.Utils
{
///
/// Utility for computing the MD5 hash of an object. _hash covers the WHOLE object row:
/// the header canon (see ) together with the Props content; a
/// non-generic RedbObject (or a typed one without Props) hashes its header alone.
///
public static class RedbHash
{
/// Canon of a null header value - distinct from an empty string.
private const string NullMark = "\0";
///
/// Canonical string of the object header: every column of the _objects row except
/// the hash itself, the identity (id, scheme id) and the audit trio
/// (date_create, date_modify, who_change). The audit trio is stamped
/// on the database record AFTER the hash is computed and never written back into the
/// object, so a hash carrying it could never be reproduced from a reloaded row - the
/// cache and the ChangeTracking hash shortcut would be dead for every object. The scheme
/// id is assigned after the batch recomputes hashes (every new object would miss its
/// first hits), and the id is 0 until the save assigns it. Header dates canonicalise at
/// second precision in UTC: sub-second digits do not survive every database (SQLite
/// stores REAL Julian days, ~40 microseconds) and MSSQL keeps the offset while
/// PostgreSQL returns UTC.
///
public static string HeaderCanon(IRedbObject obj)
{
var inv = CultureInfo.InvariantCulture;
var parts = new List(16)
{
obj.ParentId?.ToString(inv) ?? NullMark,
obj.OwnerId.ToString(inv),
Escape(obj.Name, HeaderSeparators) ?? NullMark,
Escape(obj.Note, HeaderSeparators) ?? NullMark,
obj.Key?.ToString(inv) ?? NullMark,
obj.ValueLong?.ToString(inv) ?? NullMark,
Escape(obj.ValueString, HeaderSeparators) ?? NullMark,
obj.ValueGuid?.ToString("N") ?? NullMark,
obj.ValueBool?.ToString(inv) ?? NullMark,
obj.ValueDouble?.ToString("R", inv) ?? NullMark,
obj.ValueNumeric?.ToString("G29", inv) ?? NullMark,
DateCanon(obj.ValueDatetime),
obj.ValueBytes != null ? Convert.ToBase64String(obj.ValueBytes) : NullMark,
Escape(obj.ValueUnique, HeaderSeparators) ?? NullMark,
DateCanon(obj.DateBegin),
DateCanon(obj.DateComplete),
};
return string.Join("|", parts);
}
private static string DateCanon(DateTimeOffset? value)
=> value?.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture) ?? NullMark;
///
/// Hash of the header alone (Object schemes without Props): a non-generic RedbObject or a
/// RedbObject{TProps} with Props=null. The same canon the typed hash starts from.
///
public static Guid ComputeForBaseFields(IRedbObject obj)
{
return new Guid(RedbMd5.ComputeHash(Encoding.UTF8.GetBytes(HeaderCanon(obj))));
}
///
/// Hash of any IRedbObject: header canon plus Props content.
/// Returns null if there are no Props to hash (the callers fall back to
/// ).
///
public static Guid? ComputeFor(IRedbObject obj)
{
// Find Props property via reflection
var propertiesProperty = obj.GetType().GetProperty("Props");
if (propertiesProperty != null)
{
var propertiesValue = propertiesProperty.GetValue(obj);
if (propertiesValue != null)
{
return Combine(obj, ComputeForObject(propertiesValue));
}
}
// If no Props - return null
return null;
}
public static Guid? ComputeFor(RedbObject obj) where TProps : class, new()
{
return Combine(obj, ComputeForProps(obj.Props));
}
/// Header canon and the Props hash into one object hash; null Props hash stays null.
private static Guid? Combine(IRedbObject obj, Guid? propsHash)
{
if (propsHash is null) return null;
var payload = HeaderCanon(obj) + "||" + propsHash.Value.ToString("N");
return new Guid(RedbMd5.ComputeHash(Encoding.UTF8.GetBytes(payload)));
}
public static Guid? ComputeForProps(TProps props) where TProps : class, new()
{
return ComputeForObject(props);
}
///
/// Compute hash for arbitrary object via reflection.
/// Returns null if object has no properties.
///
private static Guid? ComputeForObject(object? obj)
{
// No object → no data to hash. The reflection-based ComputeFor(IRedbObject)
// already returns null for a null Props (Props=null is a supported case —
// see ComputeForBaseFields). This aligns the generic ComputeForProps path
// with that contract instead of throwing NRE on obj.GetType().
if (obj is null) return null;
// The objects on the way from the root to this one. Reached again on the same way, an object is a cycle:
// the walk would never end and the stack overflow takes the process down. An object reached twice on
// different ways (one instance shared by two properties) is no cycle and hashes as before, as two copies.
var path = _walkPath ??= new HashSet