Path: redb/redb.Postgres/Query/PostgresTreeQueryProvider.Pvt.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.Postgres/Query/PostgresTreeQueryProvider.Pvt.cs
----
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using redb.Core.Models.Entities;
using redb.Core.Query.Base;
using redb.Core.Query.QueryExpressions;
#pragma warning disable CS0672 // Member overrides obsolete member (legacy fallback retained for HasAncestor/HasDescendant + flat search)
#pragma warning disable CS0618 // Type or member is obsolete
namespace redb.Postgres.Query;
///
/// Routes tree-subtree LINQ queries through the v2-pvt engine when the
/// generated filter contains expression-form predicates ($expr ) that
/// the legacy search_tree_objects_with_facets_base SQL function does
/// not understand. For all other tree filters we keep the legacy path
/// (faster index plans, no behavioural change).
///
public partial class PostgresTreeQueryProvider
{
///
/// Describes how a tree LINQ query is mapped onto the v2-pvt
/// pvt_build_query_sql orchestrator: which source mode to use,
/// which seed ids (if any) feed the recursive walks, whether to keep
/// the seed rows in the output, and which filter JSON to bind.
///
private readonly struct PvtTreeRoute
{
public PvtTreeRoute(string sourceMode, long[] treeIds, bool includeSeed, string filterJson)
{
SourceMode = sourceMode;
TreeIds = treeIds;
IncludeSeed = includeSeed;
FilterJson = filterJson;
}
public string SourceMode { get; }
public long[] TreeIds { get; }
public bool IncludeSeed { get; }
public string FilterJson { get; }
}
///
protected override async Task ExecuteTreeToListAsync(TreeQueryContext context, CancellationToken cancellationToken = default)
{
// Free PG: HasAncestor / HasDescendant are routed through PVT here
// because the legacy search_*_base SQL functions are gone.
var hasAncestorFilter = GetOptimizableHasAncestorFilter(context);
if (hasAncestorFilter != null)
return await ExecutePvtHasAncestorToListAsync(context, hasAncestorFilter);
var hasDescendantFilter = GetOptimizableHasDescendantFilter(context);
if (hasDescendantFilter != null)
return await ExecutePvtHasDescendantToListAsync(context, hasDescendantFilter);
if (!ShouldRoutePvtTree(context, out var route))
throw UnresolvedTreeFilter();
try
{
var objectsJson = await ExecutePvtTreeAsync(context, route);
var result = DeserializeTreeObjects(objectsJson);
if (result.Count > 0 && _lazyPropsLoader != null)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
var baseObjects = result.Cast>().ToList();
await _lazyPropsLoader.LoadPropsForManyAsync(baseObjects, context.PropsDepth);
sw.Stop();
_logger?.LogInformation("Props loaded via batch (PVT tree) in {ElapsedMs} ms", sw.ElapsedMilliseconds);
}
return (object)result;
}
catch (Exception ex)
{
_logger?.LogError(ex, "Error executing PVT tree ToList query");
throw;
}
}
///
protected override async Task ExecuteTreeCountAsync(TreeQueryContext context, CancellationToken cancellationToken = default)
{
// Free PG: HasAncestor / HasDescendant — execute list path and count.
// The two operators rewrite the context via recursive ExecuteTreeToListAsync,
// so the count cannot be issued as a single SQL aggregate at this layer.
var hasAncestorFilter = GetOptimizableHasAncestorFilter(context);
if (hasAncestorFilter != null)
{
var list = await ExecutePvtHasAncestorToListAsync(context, hasAncestorFilter);
return ((IList>)list).Count;
}
var hasDescendantFilter = GetOptimizableHasDescendantFilter(context);
if (hasDescendantFilter != null)
{
var list = await ExecutePvtHasDescendantToListAsync(context, hasDescendantFilter);
return ((IList>)list).Count;
}
if (!ShouldRoutePvtTree(context, out var route))
throw UnresolvedTreeFilter();
var inner = await BuildPvtTreeInnerSqlAsync(context, route, forCount: true);
var sql = "SELECT COUNT(*)::bigint AS \"Value\" FROM (" + inner + ") t";
object filterParam = string.IsNullOrEmpty(route.FilterJson) ? "{}" : route.FilterJson;
// A count reads no order: the inner SQL is built without one (forCount), so nothing is sorted.
long? count = await _context.ExecuteScalarAsync(sql, new object[] { filterParam }, cancellationToken);
return checked((int)(count ?? 0));
}
///
/// Is there at least one node: the inner statement of the count under EXISTS, which stops at the first node the
/// walk and the filter let through. It used to count every node. WhereHasAncestor / WhereHasDescendant resolve
/// into object ids first, as the count does, and answer by that count.
///
protected override async Task ExecuteTreeAnyAsync(TreeQueryContext context, CancellationToken cancellationToken = default)
{
if (GetOptimizableHasAncestorFilter(context) != null || GetOptimizableHasDescendantFilter(context) != null)
return await ExecuteTreeCountAsync(context, cancellationToken) > 0;
if (!ShouldRoutePvtTree(context, out var route))
throw UnresolvedTreeFilter();
var inner = await BuildPvtTreeInnerSqlAsync(context, route, forCount: true);
var sql = _sql.Query_WrapPvtWithExists(inner)
?? throw new InvalidOperationException("Query_WrapPvtWithExists returned null for a PVT-enabled dialect.");
object filterParam = string.IsNullOrEmpty(route.FilterJson) ? "{}" : route.FilterJson;
return ExistsResult(await _context.ExecuteScalarAsync(sql, new object[] { filterParam }, cancellationToken));
}
///
/// Returns true when the request can be served by the v2-pvt
/// orchestrator. Picks the appropriate p_source_mode and seed
/// id array based on the tree filters present in the context.
///
///
/// Routes covered:
///
/// WhereRoots() → tree_roots
/// WhereLeaves() → tree_leaves
/// WhereChildrenOf(id) → tree_children + tree_ids=[id]
/// WhereDescendantsOf(id) → tree_descendants + tree_ids=[id]
/// - RootObjectId / ParentIds set →
tree_descendants
/// - Whole-scheme (no root, no special filter) →
flat
/// WhereLevel(...) is attached as a $level facet
/// filter and combined with any of the above modes.
///
/// WhereHasAncestor / WhereHasDescendant are NOT served
/// here — they use their own optimized base-class path that builds
/// SQL out of two flat queries with logic inversion.
///
private bool ShouldRoutePvtTree(TreeQueryContext context, out PvtTreeRoute route)
where TProps : class, new()
{
route = new PvtTreeRoute("flat", Array.Empty(), false, "{}");
if (context.TreeFilters != null && context.TreeFilters.Any(f =>
f.Operator == TreeFilterOperator.HasAncestor ||
f.Operator == TreeFilterOperator.HasDescendant))
return false;
if (GetOptimizableHasAncestorFilter(context) != null) return false;
if (GetOptimizableHasDescendantFilter(context) != null) return false;
var treeFilters = context.TreeFilters ?? new List();
// Determine source_mode / tree_ids / include_seed.
var sourceMode = "flat";
long[] treeIds = Array.Empty();
var includeSeed = false;
var childrenOf = treeFilters.FirstOrDefault(f => f.Operator == TreeFilterOperator.ChildrenOf);
var descendantsOf = treeFilters.FirstOrDefault(f => f.Operator == TreeFilterOperator.DescendantsOf);
var isRoot = treeFilters.Any(f => f.Operator == TreeFilterOperator.IsRoot);
var isLeaf = treeFilters.Any(f => f.Operator == TreeFilterOperator.IsLeaf);
if (descendantsOf != null)
{
sourceMode = "tree_descendants";
treeIds = new[] { Convert.ToInt64(descendantsOf.Value, CultureInfo.InvariantCulture) };
includeSeed = false;
}
else if (childrenOf != null)
{
sourceMode = "tree_children";
treeIds = new[] { Convert.ToInt64(childrenOf.Value, CultureInfo.InvariantCulture) };
}
else if (isRoot)
{
sourceMode = "tree_roots";
// Respect root scoping: TreeQuery(rootObj).WhereRoots() means "the root of THIS tree",
// not every root in the scheme. Seed with the scoped root so the SQL restricts to it;
// an empty seed keeps the whole-scheme "all roots" behavior.
if (context.ParentIds != null && context.ParentIds.Length > 0)
treeIds = context.ParentIds;
else if (context.RootObjectId.HasValue)
treeIds = new[] { context.RootObjectId.Value };
}
else if (isLeaf)
{
sourceMode = "tree_leaves";
// Respect root scoping: TreeQuery(rootObj).WhereLeaves() means "leaves of THIS subtree",
// not every leaf in the scheme (the cross-tree leak). Seed with the scoped root so the SQL
// descends from it and applies the leaf predicate over its subtree; an empty seed keeps the
// whole-scheme "all leaves" behavior.
if (context.ParentIds != null && context.ParentIds.Length > 0)
treeIds = context.ParentIds;
else if (context.RootObjectId.HasValue)
treeIds = new[] { context.RootObjectId.Value };
}
else if (context.RootObjectId.HasValue
|| (context.ParentIds != null && context.ParentIds.Length > 0))
{
sourceMode = "tree_descendants";
treeIds = (context.ParentIds != null && context.ParentIds.Length > 0)
? context.ParentIds
: new[] { context.RootObjectId!.Value };
includeSeed = false;
}
// Build the filter JSON by combining the user .Where() predicates
// and any tree-level filters PVT understands natively ($level).
var merged = new Dictionary();
if (context.Filter != null)
{
var userJson = _facetBuilder.BuildFacetFilters(context.Filter);
if (!string.IsNullOrEmpty(userJson) && userJson != "{}")
{
using var doc = JsonDocument.Parse(userJson);
foreach (var prop in doc.RootElement.EnumerateObject())
merged[prop.Name] = prop.Value.Clone();
}
}
foreach (var tf in treeFilters)
{
if (tf.Operator != TreeFilterOperator.Level) continue;
if (tf.Value is int lvl)
merged["$level"] = lvl;
else if (tf.FilterConditions != null)
merged["$level"] = tf.FilterConditions;
}
// The tree filters after the one that gave the source narrow it, as conditions of the filter
// (WhereDescendantsOf(x).WhereLeaves(): the leaves under x). Only the first one used to be read.
var source = descendantsOf != null ? TreeFilterOperator.DescendantsOf
: childrenOf != null ? TreeFilterOperator.ChildrenOf
: isRoot ? TreeFilterOperator.IsRoot
: isLeaf ? TreeFilterOperator.IsLeaf
: (TreeFilterOperator?)null;
foreach (var tf in treeFilters)
{
if (tf.Operator == source) continue;
if (tf.Operator == TreeFilterOperator.ChildrenOf)
merged["$childrenOf"] = Convert.ToInt64(tf.Value, CultureInfo.InvariantCulture);
else if (tf.Operator == TreeFilterOperator.IsRoot)
merged["$isRoot"] = true;
else if (tf.Operator == TreeFilterOperator.IsLeaf)
merged["$isLeaf"] = true;
}
var filterJson = merged.Count == 0
? "{}"
: JsonSerializer.Serialize(merged, new JsonSerializerOptions
{
WriteIndented = false,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
});
route = new PvtTreeRoute(sourceMode, treeIds, includeSeed, filterJson);
return true;
}
///
/// Builds the inner SELECT _id ... SQL via
/// pvt_build_query_sql . The resulting SQL binds
/// $1::jsonb = filter, and (when present) $2::jsonb = order.
///
private async Task BuildPvtTreeInnerSqlAsync(
TreeQueryContext context,
PvtTreeRoute route,
bool forCount, CancellationToken cancellationToken = default) where TProps : class, new()
{
var orderByJson = context.Orderings.Count > 0
? _facetBuilder.BuildOrderBy(context.Orderings)
: null;
var hasOrder = !forCount && !string.IsNullOrEmpty(orderByJson) && orderByJson != "null" && orderByJson != "[]";
// The depth of the tree walk (TreeQuery(root, maxDepth)); none: the whole subtree. This passed MaxRecursionDepth, the
// depth of nested props, so maxDepth was ignored and every subtree stopped at 10 levels.
// WhereDescendantsOf(node, maxDepth) walks from that node, to its own depth when it has one.
var walkDepth = context.TreeFilters?.FirstOrDefault(f => f.Operator == TreeFilterOperator.DescendantsOf)?.MaxDepth
?? context.MaxDepth;
var maxDepth = walkDepth?.ToString(CultureInfo.InvariantCulture) ?? "NULL::integer";
var limitArg = forCount || !context.Limit.HasValue
? "NULL"
: context.Limit.Value.ToString(CultureInfo.InvariantCulture);
var offsetArg = forCount
? "0"
: (context.Offset ?? 0).ToString(CultureInfo.InvariantCulture);
var treeIdsLiteral = route.TreeIds.Length == 0
? "NULL::bigint[]"
: "ARRAY["
+ string.Join(",", route.TreeIds.Select(id => id.ToString(CultureInfo.InvariantCulture)))
+ "]::bigint[]";
// pvt_build_query_sql signature:
// p_scheme_id, p_filter, p_limit, p_offset, p_order, p_max_depth,
// p_distinct, p_source_mode, p_tree_ids, p_include_seed,
// p_polymorphic, p_distinct_on
// A distinct key binds $3; the order then always binds $2, NULL when there is none.
var distinctOnJson = BuildPvtDistinctOnJson(context);
var orderArg = hasOrder || distinctOnJson != null ? "$2::jsonb" : "NULL::jsonb";
var invocation = "SELECT pvt_build_query_sql("
+ context.SchemeId.ToString(CultureInfo.InvariantCulture)
+ ", $1::jsonb, " + limitArg
+ ", " + offsetArg
+ ", " + orderArg
+ ", " + maxDepth
+ ", " + (context.IsDistinct ? "true" : "false")
+ ", '" + route.SourceMode + "'"
+ ", " + treeIdsLiteral
+ ", " + (route.IncludeSeed ? "true" : "false")
+ ", true" // p_polymorphic=true matches Pro default
+ (distinctOnJson != null ? ", $3::jsonb" : "")
+ ") AS \"Value\"";
object filterParam = string.IsNullOrEmpty(route.FilterJson) ? "{}" : route.FilterJson;
string? inner;
if (distinctOnJson != null)
inner = await _context.ExecuteScalarAsync(invocation,
new object[] { filterParam, hasOrder ? (object)orderByJson! : DBNull.Value, distinctOnJson }, cancellationToken);
else if (hasOrder)
inner = await _context.ExecuteScalarAsync(invocation, new object[] { filterParam, orderByJson! }, cancellationToken);
else
inner = await _context.ExecuteScalarAsync(invocation, new object[] { filterParam }, cancellationToken);
if (string.IsNullOrWhiteSpace(inner))
throw new InvalidOperationException(
"pvt_build_query_sql returned an empty SQL string for tree query (scheme " + context.SchemeId + ").");
return inner;
}
///
/// Wraps the inner _id list with the same jsonb_agg(jsonb_build_object(...))
/// shape produced by the legacy search_tree_objects_with_facets_base
/// function and executes it. Returns the raw JSON array string.
///
private async Task ExecutePvtTreeAsync(
TreeQueryContext context,
PvtTreeRoute route, CancellationToken cancellationToken = default) where TProps : class, new()
{
var inner = await BuildPvtTreeInnerSqlAsync(context, route, forCount: false);
var sql =
"SELECT jsonb_agg(jsonb_build_object("
+ "'id', o._id,"
+ "'name', o._name,"
+ "'scheme_id', o._id_scheme,"
+ "'parent_id', o._id_parent,"
+ "'owner_id', o._id_owner,"
+ "'who_change_id', o._id_who_change,"
+ "'date_create', o._date_create,"
+ "'date_modify', o._date_modify,"
+ "'date_begin', o._date_begin,"
+ "'date_complete', o._date_complete,"
+ "'key', o._key,"
+ "'value_long', o._value_long,"
+ "'value_string', o._value_string,"
+ "'value_unique', o._value_unique,"
+ "'value_guid', o._value_guid,"
+ "'note', o._note,"
+ "'value_bool', o._value_bool,"
+ "'value_double', o._value_double,"
+ "'value_numeric', o._value_numeric,"
+ "'value_datetime', o._value_datetime,"
+ "'value_bytes', o._value_bytes,"
+ "'hash', o._hash"
// The order of the inner query is carried explicitly: the inner query numbers its rows in its own order
// (_ord, module 0.7.26). Aggregating over the join without ORDER BY kept it only while the planner happened
// to choose a nested loop, and row_number() OVER () above the subquery relied on the plan reading it in order.
+ ") ORDER BY sub._ord)::text AS \"Value\""
+ " FROM (" + inner + ") sub"
+ " JOIN _objects o ON o._id = sub._id";
object filterParam = string.IsNullOrEmpty(route.FilterJson) ? "{}" : route.FilterJson;
var orderByJson = context.Orderings.Count > 0
? _facetBuilder.BuildOrderBy(context.Orderings)
: null;
var hasOrder = !string.IsNullOrEmpty(orderByJson) && orderByJson != "null" && orderByJson != "[]";
if (hasOrder)
return await _context.ExecuteScalarAsync(sql, new object[] { filterParam, orderByJson! }, cancellationToken);
return await _context.ExecuteScalarAsync(sql, new object[] { filterParam }, cancellationToken);
}
///
/// SQL preview of a tree query: the statement pvt_build_query_sql compiles for it, with
/// the values it binds listed above it. The base implementation asks the database for
/// get_search_tree_sql_preview_base , a function of the retired search module that this
/// provider no longer installs, so ToSqlStringAsync on a tree query failed with 42883.
///
public override async Task GetSqlPreviewAsync(
TreeQueryContext context, CancellationToken cancellationToken = default)
{
if (!ShouldRoutePvtTree(context, out var route))
return await base.GetSqlPreviewAsync(context, cancellationToken);
var inner = await BuildPvtTreeInnerSqlAsync(context, route, forCount: false, cancellationToken);
var orderByJson = context.Orderings.Count > 0 ? _facetBuilder.BuildOrderBy(context.Orderings) : null;
var sb = new System.Text.StringBuilder();
sb.Append("-- $1 (filter) = ").AppendLine(string.IsNullOrEmpty(route.FilterJson) ? "{}" : route.FilterJson);
if (!string.IsNullOrEmpty(orderByJson) && orderByJson != "null" && orderByJson != "[]")
sb.Append("-- $2 (order) = ").AppendLine(orderByJson);
sb.Append(inner);
return sb.ToString();
}
}