Path: redb/redb.MSSql/Query/MssqlTreeQueryProvider.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.MSSql/Query/MssqlTreeQueryProvider.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.MSSql.Query; /// /// Free MSSql: implements WhereHasAncestor / WhereHasDescendant /// via the v2-pvt orchestrator (the legacy search_*_with_facets_base /// SQL helpers throw on this dialect). Port of the PostgreSQL /// PostgresTreeQueryProvider.PvtHasFilter partial. /// public partial class MssqlTreeQueryProvider { /// /// 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; } 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>(); 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 via /// dbo.pvt_build_query_sql 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" : "N'[" + string.Join(",", scopeRootIds.Select(id => id.ToString(CultureInfo.InvariantCulture))) + "]'"; var maxDepth = searchDepth; // 12-arg call: scheme, $1=filter, NULL limit, 0 offset, NULL order, // max_depth, 0 distinct, source_mode, tree_ids, 0 include_seed, // 1 polymorphic, NULL distinct_on. var invocation = "SELECT dbo.pvt_build_query_sql(" + filter.TargetSchemeId.Value.ToString(CultureInfo.InvariantCulture) + ", $1, NULL, 0, NULL, " + maxDepth.ToString(CultureInfo.InvariantCulture) + ", 0, N'" + sourceMode + "', " + treeIdsLiteral + ", 0, 1, NULL) AS [Value]"; object filterParam = string.IsNullOrEmpty(conditionJson) || conditionJson == "null" ? (object)"{}" : (object)conditionJson; _logger?.LogDebug( "PVT HasAncestor/Descendant Build (MSSql): 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(); } }