Path: redb/redb.Postgres/Query/PostgresTreeQueryProvider.PvtHasFilter.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.PvtHasFilter.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.Tasks;
using Microsoft.Extensions.Logging;
using redb.Core.Models.Entities;
using redb.Core.Query.Base;
using redb.Core.Query.QueryExpressions;
#pragma warning disable CS0618 // ExecuteTreeToListAsync base is [Obsolete] (provider overrides it).
namespace redb.Postgres.Query;
///
/// Free PG: implements WhereHasAncestor / WhereHasDescendant
/// via the v2-pvt orchestrator (the legacy search_*_with_facets_base
/// SQL helpers were removed). Mirrors the inversion logic used by the Pro
/// CTE+PVT path: find the target ids first, then recurse back into
/// with a
/// rewritten .
///
public partial class PostgresTreeQueryProvider
{
///
/// WhereHasAncestor by inversion:
/// * the ids of the objects of hasAncestorFilter.TargetSchemeId that match the inner condition, looked for
/// below the start of the query as deep as the query reaches;
/// * their descendants down to the filter's maxDepth (counted up from the returned object: 1 = the parent);
/// * the query itself, with the filter replaced by a condition on those ids, so its start, depth, Where and
/// paging apply as to any other query.
///
private async Task ExecutePvtHasAncestorToListAsync(
TreeQueryContext context,
TreeFilter hasAncestorFilter, CancellationToken cancellationToken = default) where TProps : class, new()
{
var ancestorIds = await FindIdsViaPvtAsync(hasAncestorFilter, QueryStart(context), context.MaxDepth ?? 50, cancellationToken);
if (ancestorIds.Length == 0)
return new List>();
var idsString = string.Join(",", ancestorIds.Select(id => id.ToString(CultureInfo.InvariantCulture)));
var sql = _sql.Query_GetDescendantIdsFromAncestorsSql(idsString, hasAncestorFilter.MaxDepth ?? 50);
var ids = await _context.QueryScalarListAsync(sql, System.Array.Empty(), cancellationToken);
if (ids.Count == 0)
return new List>();
return await ExecuteTreeToListAsync(WithIdsInstead(context, hasAncestorFilter, ids));
}
/// The nodes the query starts from: its root, or its parents; null for the whole scheme.
private static long[]? QueryStart(TreeQueryContext context) where TProps : class, new() =>
context.RootObjectId.HasValue ? new[] { context.RootObjectId.Value }
: context.ParentIds is { Length: > 0 } ? context.ParentIds
: null;
/// The query without , its object id confined to .
protected static TreeQueryContext WithIdsInstead(
TreeQueryContext context, TreeFilter treeFilter, IReadOnlyCollection ids) where TProps : class, new()
{
var idsFilter = new InExpression(
new redb.Core.Query.QueryExpressions.PropertyInfo("_id", typeof(long), true),
ids.Cast().ToList());
var rewritten = context.Clone();
rewritten.TreeFilters = new List(context.TreeFilters.Where(f => f != treeFilter));
rewritten.Filter = rewritten.Filter != null
? new LogicalExpression(LogicalOperator.And, new FilterExpression[] { rewritten.Filter, idsFilter })
: idsFilter;
return rewritten;
}
///
/// Step 1+2+3 of WhereHasDescendant inversion:
/// * find descendant ids of hasDescendantFilter.TargetSchemeId matching the inner condition;
/// * walk up via Query_GetParentIdsFromDescendantsSql to collect every ancestor id;
/// * rewrite the context (drop HasDescendant filter, AND-merge an
/// on _id ) and recurse.
///
private async Task ExecutePvtHasDescendantToListAsync(
TreeQueryContext context,
TreeFilter hasDescendantFilter, CancellationToken cancellationToken = default) where TProps : class, new()
{
var descendantIds = await FindIdsViaPvtAsync(hasDescendantFilter, scopeRootIds: null,
searchDepth: hasDescendantFilter.MaxDepth ?? 50, cancellationToken);
if (descendantIds.Length == 0)
return new List>();
// Walk up the parent chain to collect every potential matching object id.
var depthLimit = hasDescendantFilter.MaxDepth ?? 50;
var idsString = string.Join(",", descendantIds.Select(id => id.ToString(CultureInfo.InvariantCulture)));
var sql = _sql.Query_GetParentIdsFromDescendantsSql(idsString, depthLimit);
var parentIdList = await _context.QueryScalarListAsync(sql, System.Array.Empty(), cancellationToken);
var parentIds = parentIdList.ToArray();
if (parentIds.Length == 0)
return new List>();
var idsFilter = new InExpression(
new redb.Core.Query.QueryExpressions.PropertyInfo("_id", typeof(long), true),
parentIds.Cast().ToList());
var optimizedContext = context.Clone();
optimizedContext.TreeFilters = new List(
context.TreeFilters.Where(f => f != hasDescendantFilter));
optimizedContext.Filter = optimizedContext.Filter != null
? new LogicalExpression(LogicalOperator.And, new FilterExpression[] { optimizedContext.Filter, idsFilter })
: (FilterExpression)idsFilter;
return await ExecuteTreeToListAsync(optimizedContext);
}
///
/// Compiles the inner SELECT _id ... SQL for the given tree filter
/// (HasAncestor / HasDescendant — both use the same flat or
/// tree_descendants route depending on )
/// via pvt_build_query_sql , then executes it and returns the
/// matching object ids.
///
private async Task FindIdsViaPvtAsync(TreeFilter filter, long[]? scopeRootIds, int searchDepth, CancellationToken cancellationToken = default)
{
if (filter.TargetSchemeId is null || filter.TargetSchemeId.Value == 0)
return Array.Empty();
var conditionJson = JsonSerializer.Serialize(
filter.FilterConditions,
new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping });
var sourceMode = scopeRootIds != null && scopeRootIds.Length > 0 ? "tree_descendants" : "flat";
var treeIdsLiteral = scopeRootIds == null || scopeRootIds.Length == 0
? "NULL::bigint[]"
: "ARRAY[" + string.Join(",", scopeRootIds.Select(id => id.ToString(CultureInfo.InvariantCulture))) + "]::bigint[]";
var maxDepth = searchDepth;
var invocation = "SELECT pvt_build_query_sql("
+ filter.TargetSchemeId.Value.ToString(CultureInfo.InvariantCulture)
+ ", $1::jsonb, NULL, 0, NULL::jsonb, "
+ maxDepth.ToString(CultureInfo.InvariantCulture)
+ ", false, '" + sourceMode + "', " + treeIdsLiteral
+ ", false, true) AS \"Value\"";
object filterParam = string.IsNullOrEmpty(conditionJson) || conditionJson == "null"
? (object)"{}"
: (object)conditionJson;
_logger?.LogDebug(
"PVT HasAncestor/Descendant Build: TargetSchemeId={SchemeId}, Mode={Mode}, Scope={Scope}, Cond={Cond}",
filter.TargetSchemeId.Value, sourceMode, treeIdsLiteral, conditionJson);
var inner = await _context.ExecuteScalarAsync(invocation, new object[] { filterParam }, cancellationToken);
if (string.IsNullOrWhiteSpace(inner))
return Array.Empty();
var idSql = "SELECT _id AS \"Value\" FROM (" + inner + ") sub";
var ids = await _context.QueryScalarListAsync(idSql, System.Array.Empty(), cancellationToken);
return ids.ToArray();
}
}