Path: redb-route/redb.Route.Core/Extensions/RedbStorageDslExtensions.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.Core/Extensions/RedbStorageDslExtensions.cs
----
using System.Reflection;
using redb.Core;
using redb.Core.Models.Contracts;
using redb.Core.Models.Entities;
using redb.Core.Serialization;
using redb.Route.Abstractions;
using redb.Route.Expressions;
namespace redb.Route.RedbCore.Extensions;
///
/// Declarative storage verbs over — the string/Type-parameterized
/// counterparts of the lambda verbs in , designed for the XML
/// markup (a lambda cannot live in markup) and equally usable from C#.
///
/// Every verb resolves the service per exchange through
/// — the same
/// scoped model the lambda verbs use — and participates in an ambient redb transaction opened by
/// BeginRedbTransaction() like any other redb call on that service.
///
///
public static class RedbStorageDslExtensions
{
// ── Get (typed) ──────────────────────────────────────────────────
///
/// Loads a RedbObject<TProps> by id and stores it into the target
/// (body by default).
///
/// Route definition.
/// The props CLR type (markup: resolved via the bean type resolver).
/// Expression producing the object id (e.g. ${header.orderId}).
/// Materialization depth for nested objects.
/// Named ; null/empty — the default one.
/// Where the result goes: body (default), header:Name, property:Name.
public static IRouteDefinition RedbGet(
this IRouteDefinition route,
Type propsType,
string idExpression,
int depth = 10,
string? storage = null,
string? target = null)
{
ArgumentNullException.ThrowIfNull(propsType);
ArgumentException.ThrowIfNullOrEmpty(idExpression);
// Reflection once at definition time, a compiled delegate per message.
var load = (Func>)LoadHelperDef
.MakeGenericMethod(propsType)
.CreateDelegate(typeof(Func>));
var idExpr = new StringExpression(idExpression);
var store = ParseTarget(target);
return route.Process(async (exchange, ct) =>
{
var redb = Resolve(route, exchange, storage);
var id = idExpr.Evaluate(exchange);
store(exchange, await load(redb, id, depth));
});
}
// ── Get (raw JSON, no CLR type) ──────────────────────────────────
///
/// Loads the whole object as raw JSON by id — the in-database materializer
/// (get_object_json) serializes the full tree; no props CLR type is needed, so a
/// pure-markup module without any assembly can read redb objects. The JSON string goes to
/// the target (body by default); a missing object stores null (or throws, per the redb
/// configuration's ThrowOnObjectNotFound).
///
public static IRouteDefinition RedbGetJson(
this IRouteDefinition route,
string idExpression,
int depth = 10,
string? storage = null,
string? target = null)
{
ArgumentException.ThrowIfNullOrEmpty(idExpression);
var idExpr = new StringExpression(idExpression);
var store = ParseTarget(target);
return route.Process(async (exchange, ct) =>
{
var redb = Resolve(route, exchange, storage);
var id = idExpr.Evaluate(exchange);
store(exchange, await redb.LoadJsonAsync(id, depth));
});
}
// ── Save ─────────────────────────────────────────────────────────
///
/// Saves the exchange body to redb storage and puts the saved object's id into the exchange
/// body's object (the body keeps the saved ; a JSON body is
/// materialized first). Body cases:
///
/// an — saved as is ( optional);
/// a JSON string — deserialized to RedbObject<TProps> via
/// (required for this case), then saved.
///
///
/// Route definition.
/// The props CLR type; required only when the body is JSON.
/// Save through the declared unique keys (SaveByUniqueAsync) —
/// requires .
/// Named ; null/empty — the default one.
public static IRouteDefinition RedbSave(
this IRouteDefinition route,
Type? propsType = null,
bool byUnique = false,
string? storage = null)
{
if (byUnique && propsType is null)
throw new ArgumentException(
"RedbSave(byUnique: true) needs the props type — SaveByUniqueAsync is typed.",
nameof(propsType));
var saveByUnique = byUnique
? (Func>)SaveByUniqueHelperDef
.MakeGenericMethod(propsType!)
.CreateDelegate(typeof(Func>))
: null;
return route.Process(async (exchange, ct) =>
{
var redb = Resolve(route, exchange, storage);
var obj = MaterializeBody(exchange, propsType);
if (saveByUnique is not null)
await saveByUnique(redb, obj);
else
await redb.SaveAsync(obj);
exchange.In.Body = obj; // the saved object (with its id) is the step's result
});
}
// ── Query ────────────────────────────────────────────────────────
///
/// A server-side query: the condition string is translated onto
/// redb Where over props, onto redb WhereRedb over
/// the base fields of the stored object (Id, ParentId, ValueGuid,
/// ValueString, DateCreate…), both by
/// (comparisons, AND/OR/NOT, contains/startsWith/endsWith; value-side subtrees — headers,
/// functions, date arithmetic — fold per message into constants; the untranslatable refuses
/// at route build). The two conditions combine with AND: the storage cannot mix base fields
/// and props inside one OR. The result list of RedbObject<TProps> goes to the target.
/// Order of application: whereRedb → where → filter spec → orderBy/orderByRedb → skip → take.
///
/// Route definition.
/// The props CLR type to query.
/// Condition over props in the route language; null — no condition.
/// Props property path to order by; null — storage order.
/// Order direction for or .
/// Row limit.
/// Rows to skip.
/// Registry name of an — the
/// full-LINQ escape hatch for what the string cannot say.
/// Named ; null/empty — the default one.
/// Where the list goes: body (default), header:Name, property:Name.
/// Condition over the base fields of the stored object; null — no condition.
/// Base field to order by, instead of .
/// What goes to the target: the list (default), the first object or
/// null, the number of matches, or whether anything matched.
public static IRouteDefinition RedbQuery(
this IRouteDefinition route,
Type propsType,
string? where = null,
string? orderBy = null,
bool descending = false,
int? take = null,
int? skip = null,
string? filter = null,
string? storage = null,
string? target = null,
string? whereRedb = null,
string? orderByRedb = null,
RedbQueryOutput outputType = RedbQueryOutput.List)
{
ArgumentNullException.ThrowIfNull(propsType);
// Only a list pulls every matching row into memory; one object, a count or a yes/no does not.
if (outputType == RedbQueryOutput.List && where is null && whereRedb is null && filter is null && orderBy is null && orderByRedb is null
&& take is null && skip is null)
throw new ArgumentException(
"RedbQuery without where/whereRedb/filter/orderBy/orderByRedb/take/skip would be a full unbounded scan — say what you want.",
nameof(where));
if (orderBy is not null && orderByRedb is not null)
throw new ArgumentException(
"RedbQuery orders by one key: orderBy (a props path) or orderByRedb (a base field), not both.",
nameof(orderByRedb));
if (outputType == RedbQueryOutput.First && take is not null)
throw new ArgumentException(
"RedbQuery outputType First reads one object — take does not apply (skip and ordering do).",
nameof(take));
if (outputType is RedbQueryOutput.Count or RedbQueryOutput.Any
&& (orderBy is not null || orderByRedb is not null || take is not null || skip is not null))
throw new ArgumentException(
$"RedbQuery outputType {outputType} answers for all the matches — orderBy/orderByRedb/take/skip do not apply.",
nameof(outputType));
// Everything translatable is translated NOW — a broken condition fails the route build.
var props = Query.QueryRoot.Props(propsType);
var wherePlan = where is null ? null : Query.RedbQueryTranslator.TranslateWhere(props, where);
var whereRedbPlan = whereRedb is null ? null : Query.RedbQueryTranslator.TranslateWhere(Query.QueryRoot.Base, whereRedb);
var orderPlan = orderBy is not null ? Query.RedbQueryTranslator.TranslateOrderBy(props, orderBy)
: orderByRedb is not null ? Query.RedbQueryTranslator.TranslateOrderBy(Query.QueryRoot.Base, orderByRedb)
: null;
var store = ParseTarget(target);
var execute = (Func>)QueryHelperDef
.MakeGenericMethod(propsType)
.CreateDelegate(typeof(Func>), new QueryPlan
{
Where = wherePlan,
WhereRedb = whereRedbPlan,
OrderBy = orderPlan,
OrderByBase = orderByRedb is not null,
Descending = descending,
Take = take,
Skip = skip,
FilterName = filter,
Output = outputType,
});
return route.Process(async (exchange, ct) =>
{
var redb = Resolve(route, exchange, storage);
var context = route.GetContext()
?? throw new InvalidOperationException("RouteContext is not available.");
store(exchange, await execute(redb, exchange, context));
});
}
// ── Delete ───────────────────────────────────────────────────────
///
/// Deletes an object by id (no props type needed). The body is left untouched; the outcome
/// (true — deleted, false — not found) goes into the redbDeleted header.
///
public static IRouteDefinition RedbDelete(
this IRouteDefinition route,
string idExpression,
string? storage = null)
{
ArgumentException.ThrowIfNullOrEmpty(idExpression);
var idExpr = new StringExpression(idExpression);
return route.Process(async (exchange, ct) =>
{
var redb = Resolve(route, exchange, storage);
var id = idExpr.Evaluate(exchange);
exchange.In.Headers["redbDeleted"] = await redb.DeleteAsync(id);
});
}
// ── helpers ──────────────────────────────────────────────────────
private static IRedbService Resolve(IRouteDefinition route, IExchange exchange, string? storage)
=> string.IsNullOrEmpty(storage)
? RedbRouteExtensions.ResolveRedbService(route, exchange)
: (route.GetContext() ?? throw new InvalidOperationException(
"RouteContext is not available. Ensure the route builder has been configured."))
.GetRedbService(storage, exchange);
private static readonly MethodInfo LoadHelperDef = typeof(RedbStorageDslExtensions)
.GetMethod(nameof(LoadHelper), BindingFlags.NonPublic | BindingFlags.Static)!;
private static async Task