Path: redb/redb.SQLite/Query/SqliteTreeQueryProvider.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.SQLite/Query/SqliteTreeQueryProvider.Pvt.cs ---- using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; 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.SQLite.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 SqliteTreeQueryProvider { /// /// 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 rows = await ExecutePvtTreeAsync(context, route, cancellationToken); var result = rows.Select(MapRowToTreeObject).ToList(); 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(*) 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"; var limitArg = forCount || !context.Limit.HasValue ? "NULL" : context.Limit.Value.ToString(CultureInfo.InvariantCulture); var offsetArg = forCount ? "0" : (context.Offset ?? 0).ToString(CultureInfo.InvariantCulture); // SQLite: p_tree_ids is a JSON array text (parsed by pvtInListFromJsonArray), not a PG bigint[]. var treeIdsLiteral = route.TreeIds.Length == 0 ? "NULL" : "'[" + string.Join(",", route.TreeIds.Select(id => id.ToString(CultureInfo.InvariantCulture))) + "]'"; // 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 // SQLite has no ::type casts; booleans pass as 1/0. // 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" : "NULL"; var invocation = "SELECT pvt_build_query_sql(" + context.SchemeId.ToString(CultureInfo.InvariantCulture) + ", $1, " + limitArg + ", " + offsetArg + ", " + orderArg + ", " + maxDepth + ", " + (context.IsDistinct ? "1" : "0") + ", '" + route.SourceMode + "'" + ", " + treeIdsLiteral + ", " + (route.IncludeSeed ? "1" : "0") + ", 1" // p_polymorphic=1 matches Pro default + (distinctOnJson != null ? ", json($3)" : "") + ") 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; } /// /// 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 the native /// SQLite extension does not host, so ToSqlStringAsync on a tree query failed with /// "no such function: get_search_tree_sql_preview_base" (E204). /// 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 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(); } /// /// Reads the _objects rows of the inner _id list, in its order. Props are not read here: the /// caller loads them once through the lazy loader (this wrapper used to build each object's JSON with /// get_object_json, and the loader built it again). /// 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 = _sql.Query_WrapPvtWithObjectRows(inner) ?? throw new InvalidOperationException("Query_WrapPvtWithObjectRows returned null for the SQLite dialect."); 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.QueryAsync(sql, new object[] { filterParam, orderByJson! }, cancellationToken); return await _context.QueryAsync(sql, new object[] { filterParam }, cancellationToken); } }