Path: redb-route/redb.Route.Sql/Batch/BatchItemAccessor.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Batch/BatchItemAccessor.cs
----
using System.Collections;
using System.Collections.Concurrent;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Xml.Linq;
using redb.Route.Sql.Mapping;
namespace redb.Route.Sql.Batch;
/// Result of looking a name up in a batch item.
internal enum ItemLookup
{
/// The item has a value for the name, possibly null.
Found,
/// The item has named values, but none for this name.
Missing,
/// Several keys equal the name ignoring case and none equals it exactly.
Ambiguous,
/// The item is null, a scalar, a collection, an XML node or another .NET type: it has no named values at all.
NoNamedValues,
}
///
/// Reads a named value out of a batch item in whatever shape the route produced it: a dictionary (generic, read-only or
/// non-generic — CSV rows are Dictionary<string, string>), a JSON object (,
/// , or a whose root is one), or a POCO. A key equal to the name wins;
/// failing that, the single key equal to it ignoring case — two such keys name nothing. POCO properties match by the rule that
/// maps result columns to properties ().
///
/// A POCO is a type of the application: the properties of a .NET type (, ,
/// ) are not the fields of a record. An XML node carries no named values, as in Apache Camel, where
/// a DOM node is iterated but only a Map is looked up by key; its values are bound with xpath expressions.
///
///
internal static class BatchItemAccessor
{
// Weak per type: a POCO of an unloadable module (collectible load context) does not stay alive in this cache.
private static readonly System.Runtime.CompilerServices.ConditionalWeakTable PocoShapes = new();
/// A POCO type's readable properties (null: no named values) and the property each name matched.
private sealed class PocoShape(PropertyInfo[]? properties)
{
public PropertyInfo[]? Properties { get; } = properties;
public ConcurrentDictionary Matches { get; } = new(StringComparer.Ordinal);
}
/// Looks up in a batch item: by key in a map or JSON object, by property in a POCO.
internal static ItemLookup Find(object? item, string name, out object? value) => Find(item, name, readProperties: true, out value);
///
/// Looks up by key only — in a map or a JSON object. This is how the body of a single statement is
/// read, as in Apache Camel, where a body that converts to a Map (Jackson's JsonNode included) is looked up
/// by key and a POJO is not.
///
internal static ItemLookup FindByKey(object? item, string name, out object? value) => Find(item, name, readProperties: false, out value);
private static ItemLookup Find(object? item, string name, bool readProperties, out object? value)
{
value = null;
switch (item)
{
case IDictionary dictionary:
if (dictionary.TryGetValue(name, out value))
return ItemLookup.Found;
return FindIgnoringCase(dictionary.Keys, name, key => dictionary[key], out value);
case IReadOnlyDictionary readOnly:
if (readOnly.TryGetValue(name, out value))
return ItemLookup.Found;
return FindIgnoringCase(readOnly.Keys, name, key => readOnly[key], out value);
case JsonElement { ValueKind: JsonValueKind.Object } json:
if (json.TryGetProperty(name, out var property))
{
value = property;
return ItemLookup.Found;
}
return FindIgnoringCase(json.EnumerateObject().Select(p => p.Name), name, key => json.GetProperty(key), out value);
case JsonDocument document:
return Find(document.RootElement, name, out value);
case JsonObject jsonObject:
if (jsonObject.TryGetPropertyValue(name, out var node))
{
value = node;
return ItemLookup.Found;
}
return FindIgnoringCase(jsonObject.Select(p => p.Key), name, key => jsonObject[key], out value);
case IDictionary nonGeneric:
if (nonGeneric.Contains(name))
{
value = nonGeneric[name];
return ItemLookup.Found;
}
return FindIgnoringCase(nonGeneric.Keys.OfType(), name, key => nonGeneric[key], out value);
case null:
case JsonElement:
case JsonNode:
case XObject:
case IEnumerable:
return ItemLookup.NoNamedValues;
default:
return readProperties ? FindProperty(item, name, out value) : ItemLookup.NoNamedValues;
}
}
/// The item is XML (a LINQ to XML object or a DOM node), whose values are reached with xpath expressions.
internal static bool IsXml(object? item) => item is XObject or System.Xml.XmlNode;
/// The entries of a dictionary item, which an item's ${header.name} expressions see; nothing for other shapes.
internal static IEnumerable> Entries(object? item) => item switch
{
IDictionary dictionary => dictionary,
IReadOnlyDictionary readOnly => readOnly,
IDictionary nonGeneric => nonGeneric.Keys.OfType().Select(key => new KeyValuePair(key, nonGeneric[key])),
_ => [],
};
private static ItemLookup FindIgnoringCase(IEnumerable keys, string name, Func read, out object? value)
{
value = null;
string? match = null;
foreach (var key in keys)
{
if (!string.Equals(key, name, StringComparison.OrdinalIgnoreCase))
continue;
if (match is not null)
return ItemLookup.Ambiguous;
match = key;
}
if (match is null)
return ItemLookup.Missing;
value = read(match);
return ItemLookup.Found;
}
private static ItemLookup FindProperty(object item, string name, out object? value)
{
value = null;
var type = item.GetType();
var shape = PocoShapes.GetValue(type, static t => new PocoShape(ReadableProperties(t)));
if (shape.Properties is not { } properties)
return ItemLookup.NoNamedValues;
var property = shape.Matches.GetOrAdd(name, static (key, all) => ColumnNameMatcher.Find(all, key), properties);
if (property is null)
return ItemLookup.Missing;
value = property.GetValue(item);
return ItemLookup.Found;
}
///
/// Public readable instance properties of a POCO; null for a type that carries no named values: a scalar, or any type of
/// .NET itself (System.*, Microsoft.*). Anonymous types and records of the application are POCOs.
///
private static PropertyInfo[]? ReadableProperties(Type type)
{
if (type.IsPrimitive || type.IsEnum || IsFrameworkType(type))
return null;
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.GetMethod is { IsPublic: true } && p.GetIndexParameters().Length == 0)
.ToArray();
return properties.Length == 0 ? null : properties;
}
private static bool IsFrameworkType(Type type) =>
type.Namespace is { } ns
&& (ns == "System" || ns.StartsWith("System.", StringComparison.Ordinal)
|| ns == "Microsoft" || ns.StartsWith("Microsoft.", StringComparison.Ordinal));
}