Path: redb/redb.Core/Query/RedbProjectedQueryable.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.Core/Query/RedbProjectedQueryable.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using redb.Core.Models.Entities; using redb.Core.Query.Projection; namespace redb.Core.Query; /// /// Implementation of LINQ query projections in REDB with filtering and sorting support /// OPTIMIZED: Uses ProjectionFieldExtractor to load only required fields /// public class RedbProjectedQueryable : IRedbProjectedQueryable where TProps : class, new() { private readonly IRedbQueryable _sourceQuery; private readonly Expression, TResult>> _projection; // Provider and SchemeId for optimized loading private readonly IRedbQueryProvider? _provider; private readonly long _schemeId; // Chain of operations to execute after projection private readonly List>> _wherePredicates = new(); private readonly List<(Expression KeySelector, bool IsDescending)> _orderByExpressions = new(); private readonly bool _isDistinct; // Distinct flag for projection // S-4 (решение владельца 2026-09-04): Take/Skip, вызванные ПОСЛЕ операций, исполняемых в // памяти (Where/OrderBy/Distinct после Select), не уходят в источник - иначе сервер отрезал // бы страницу ДО фильтра и строки молча терялись. Такие Take/Skip копятся здесь и // применяются в памяти. Конвейер: Where* -> OrderBy* -> Distinct -> Skip/Take (в порядке // вызова). Take/Skip ДО первой in-memory операции уходят в источник, как раньше. private readonly List<(bool IsSkip, int Count)> _pagingOps = new(); // Источник уже получил серверный Take/Skip (fast-path): пуш последующих Where в источник // запрещён - иначе фильтр применился бы ДО лимита и порядок вызовов был бы нарушен. private readonly bool _sourcePaged; // The ordering after Select went to the source (OrderBy of a member the source can sort by, nothing in memory // before it): a ThenBy continues it there, and a later Take/Skip stays a LIMIT/OFFSET of the source. private readonly bool _sourceOrdered; // Extracted structure_ids for optimized loading private HashSet? _projectedStructureIds; // Text field paths for SQL function search_objects_with_projection_by_paths private List? _projectedFieldPaths; private readonly ProjectionFieldExtractor _fieldExtractor = new(); public RedbProjectedQueryable( IRedbQueryable sourceQuery, Expression, TResult>> projection) { _sourceQuery = sourceQuery; _projection = projection; } /// /// Constructor with provider for optimized loading /// public RedbProjectedQueryable( IRedbQueryable sourceQuery, Expression, TResult>> projection, IRedbQueryProvider provider, long schemeId) { _sourceQuery = sourceQuery; _projection = projection; _provider = provider; _schemeId = schemeId; } // Private constructor for creating copies with additional operations private RedbProjectedQueryable( IRedbQueryable sourceQuery, Expression, TResult>> projection, List>> wherePredicates, List<(Expression KeySelector, bool IsDescending)> orderByExpressions, HashSet? projectedStructureIds, List? projectedFieldPaths, IRedbQueryProvider? provider, long schemeId, bool isDistinct = false, List<(bool IsSkip, int Count)>? pagingOps = null, bool sourcePaged = false, bool sourceOrdered = false) { _sourceOrdered = sourceOrdered; _sourceQuery = sourceQuery; _projection = projection; _wherePredicates = new List>>(wherePredicates); _orderByExpressions = new List<(Expression, bool)>(orderByExpressions); _projectedStructureIds = projectedStructureIds; _projectedFieldPaths = projectedFieldPaths; _provider = provider; _schemeId = schemeId; _isDistinct = isDistinct; if (pagingOps != null) _pagingOps = new List<(bool IsSkip, int Count)>(pagingOps); _sourcePaged = sourcePaged; } /// /// Extracted structure_ids for optimization (for provider access) /// public HashSet? ProjectedStructureIds => _projectedStructureIds; /// /// Text field paths for SQL function search_objects_with_projection_by_paths /// public List? ProjectedFieldPaths => _projectedFieldPaths; /// /// Projection expression (for provider access) /// public Expression, TResult>> Projection => _projection; public IRedbProjectedQueryable Where(Expression> predicate) { if (predicate == null) throw new ArgumentNullException(nameof(predicate)); // S-4 шаг 2 (решение владельца 2026-09-04): предикат по простым спроецированным // props-членам транслируется ОБРАТНО В ИСТОЧНИК - фильтр и последующие Take/Skip // остаются серверными. Всё нетранслируемое (вычисляемые члены, базовые поля, r целиком) // корректно фильтруется в памяти, как раньше - страдает только скорость. При уже // накопленном локальном Take/Skip пуш запрещён: фильтр обязан видеть отрезанную // страницу (семантика порядка вызовов). if (!_sourcePaged && _pagingOps.Count == 0 && TryPushPredicateToSource(predicate, out var pushedSource)) { return new RedbProjectedQueryable( pushedSource, _projection, _wherePredicates, _orderByExpressions, _projectedStructureIds, _projectedFieldPaths, _provider, _schemeId, _isDistinct, _pagingOps, _sourcePaged, _sourceOrdered); } var newWherePredicates = new List>>(_wherePredicates) { predicate }; return new RedbProjectedQueryable( _sourceQuery, _projection, newWherePredicates, _orderByExpressions, _projectedStructureIds, _projectedFieldPaths, _provider, _schemeId, _isDistinct, _pagingOps, _sourcePaged, _sourceOrdered); } /// /// Пытается переписать предикат над результатом проекции в предикат над TProps: члены /// результата подставляются их проекционными выражениями, цепочки x.Props.* переносятся на /// параметр TProps. Транслируются только простые member-проекции props-полей; любой другой /// случай - false, и предикат остаётся в памяти (fail-safe: корректность не зависит от пуша). /// private bool TryPushPredicateToSource( Expression> predicate, out IRedbQueryable pushed) { pushed = _sourceQuery; var map = ProjectionMembers(); if (map == null) return false; var pParam = Expression.Parameter(typeof(TProps), "p"); var rewriter = new ProjectedPredicateRewriter( predicate.Parameters[0], map, _projection.Parameters[0], pParam); var body = rewriter.Visit(predicate.Body); if (!rewriter.Success || body == null) return false; pushed = _sourceQuery.Where(Expression.Lambda>(body, pParam)); return true; } private sealed class ProjectedPredicateRewriter : ExpressionVisitor { private readonly ParameterExpression _rParam; private readonly Dictionary _map; private readonly ParameterExpression _xParam; private readonly ParameterExpression _pParam; public bool Success { get; private set; } = true; public ProjectedPredicateRewriter( ParameterExpression rParam, Dictionary map, ParameterExpression xParam, ParameterExpression pParam) { _rParam = rParam; _map = map; _xParam = xParam; _pParam = pParam; } protected override Expression VisitMember(MemberExpression node) { if (node.Expression == _rParam) { if (!_map.TryGetValue(node.Member.Name, out var mapped)) { Success = false; return node; } var translated = TranslateProjectionExpr(mapped); if (translated == null) { Success = false; return node; } return translated; } return base.VisitMember(node); } protected override Expression VisitParameter(ParameterExpression node) { if (node == _rParam) Success = false; // r используется целиком - такое не транслируем return base.VisitParameter(node); } /// x.Props.<chain> -> p.<chain>; всё прочее (x.Id, вычисления) - null. private Expression? TranslateProjectionExpr(Expression expr) { while (expr is UnaryExpression u && (u.NodeType == ExpressionType.Convert || u.NodeType == ExpressionType.ConvertChecked)) expr = u.Operand; var chain = new Stack(); var cur = expr; while (cur is MemberExpression m) { if (m.Member.Name == "Props" && m.Expression == _xParam) { Expression acc = _pParam; while (chain.Count > 0) acc = Expression.MakeMemberAccess(acc, chain.Pop()); return acc; } chain.Push(m.Member); cur = m.Expression; } return null; } } // The ordering after Select is the ordering of the objects the projection reads: a key that is a projected Props // member or one of the object's own fields sorts the source, in SQL, and // a later Take/Skip stays a LIMIT/OFFSET there. Select only shapes what the page materializes. A key the source // cannot sort by, or an ordering after operations that run in memory, sorts in memory as before (S-4). public IRedbProjectedQueryable OrderBy(Expression> keySelector) => Order(keySelector, descending: false, thenBy: false); public IRedbProjectedQueryable OrderByDescending(Expression> keySelector) => Order(keySelector, descending: true, thenBy: false); public IRedbProjectedQueryable ThenBy(Expression> keySelector) => Order(keySelector, descending: false, thenBy: true); public IRedbProjectedQueryable ThenByDescending(Expression> keySelector) => Order(keySelector, descending: true, thenBy: true); private IRedbProjectedQueryable Order(Expression> keySelector, bool descending, bool thenBy) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); if (thenBy && _orderByExpressions.Count == 0 && !_sourceOrdered) throw new InvalidOperationException("ThenBy continues an ordering: call OrderBy or OrderByDescending first."); // OrderBy starts an ordering, ThenBy continues the one that exists: in the source or in memory. var inSource = !thenBy || _orderByExpressions.Count == 0; if (inSource && !_sourcePaged && !HasInMemoryOps && TryPushOrdering(keySelector, descending, thenBy, out var ordered)) return Copy(source: ordered, sourceOrdered: true); if (thenBy && _orderByExpressions.Count == 0) throw new InvalidOperationException( "This ThenBy cannot continue the ordering the database applies (its key is not a projected Props member " + "or field of the object, or Take/Skip/Distinct came in between): put the ordering before Select."); // In memory, as before: OrderBy replaces the ordering, ThenBy adds a key to it. var keys = thenBy ? new List<(Expression, bool)>(_orderByExpressions) : new List<(Expression, bool)>(); keys.Add((keySelector, descending)); return Copy(orderBy: keys, sourceOrdered: false); } private RedbProjectedQueryable Copy( IRedbQueryable? source = null, List<(Expression KeySelector, bool IsDescending)>? orderBy = null, bool? sourceOrdered = null) => new( source ?? _sourceQuery, _projection, _wherePredicates, orderBy ?? _orderByExpressions, _projectedStructureIds, _projectedFieldPaths, _provider, _schemeId, _isDistinct, _pagingOps, _sourcePaged, sourceOrdered ?? _sourceOrdered); /// Members of the projection by name, mapped to their expressions over the object; null for another shape. private Dictionary? ProjectionMembers() { if (_projection.Body is NewExpression ne && ne.Members != null) { var map = new Dictionary(); for (int i = 0; i < ne.Members.Count; i++) map[ne.Members[i].Name] = ne.Arguments[i]; return map; } if (_projection.Body is MemberInitExpression mi && mi.NewExpression.Arguments.Count == 0) { var map = new Dictionary(); foreach (var binding in mi.Bindings) { if (binding is not MemberAssignment assignment) return null; map[assignment.Member.Name] = assignment.Expression; } return map; } return null; } // Fields of the object the source sorts by (OrderByRedb), by their IRedbObject property names. private static readonly HashSet SortableObjectFields = new(StringComparer.Ordinal) { "Id", "Name", "ParentId", "SchemeId", "DateCreate", "DateModify", "ValueLong", "ValueString", "ValueGuid", "ValueBool", "ValueDouble", "ValueNumeric", "ValueDatetime" }; /// /// The ordering of a projected member sent to the source: OrderByRedb for a field of the object, OrderBy over /// TProps for a member that reads a Props path (rewritten as Where after Select is). /// private bool TryPushOrdering( Expression> keySelector, bool descending, bool thenBy, out IRedbQueryable ordered) { ordered = _sourceQuery; // Only a provider whose ordering matches the in-memory one: Free drops objects without a value for the key // and does not apply ThenBy everywhere, so its projections keep sorting in memory. if (_provider is not Base.QueryProviderBase { SortsByPropsLikeLinq: true }) return false; var map = ProjectionMembers(); if (map == null) return false; var sorted = _sourceQuery as IOrderedRedbQueryable; if (thenBy && sorted == null) return false; if (keySelector.Body is MemberExpression member && member.Expression == keySelector.Parameters[0] && map.TryGetValue(member.Member.Name, out var mapped) && ObjectField(mapped) is { } field && field.PropertyType == typeof(TKey)) { var o = Expression.Parameter(typeof(redb.Core.Models.Contracts.IRedbObject), "o"); var byField = Expression.Lambda>(Expression.Property(o, field), o); ordered = thenBy ? descending ? sorted!.ThenByDescendingRedb(byField) : sorted!.ThenByRedb(byField) : descending ? _sourceQuery.OrderByDescendingRedb(byField) : _sourceQuery.OrderByRedb(byField); return true; } var p = Expression.Parameter(typeof(TProps), "p"); var rewriter = new ProjectedPredicateRewriter(keySelector.Parameters[0], map, _projection.Parameters[0], p); var body = rewriter.Visit(keySelector.Body); if (!rewriter.Success || body == null || body.Type != typeof(TKey) || !IsMemberChainOf(body, p)) return false; var byProps = Expression.Lambda>(body, p); ordered = thenBy ? descending ? sorted!.ThenByDescending(byProps) : sorted!.ThenBy(byProps) : descending ? _sourceQuery.OrderByDescending(byProps) : _sourceQuery.OrderBy(byProps); return true; } /// /// A plain path of Props fields (p.HomeAddress.City): the ordering of the source sorts by such a path. A key /// computed over Props members is not sent there, the ordering parser need not translate it; it sorts in memory. /// private static bool IsMemberChainOf(Expression expr, ParameterExpression p) { while (expr is MemberExpression m) expr = m.Expression!; return expr == p; } /// The field of the object a projected member reads (x.DateCreate), if the source can sort by it. private System.Reflection.PropertyInfo? ObjectField(Expression mapped) { while (mapped is UnaryExpression u && (u.NodeType == ExpressionType.Convert || u.NodeType == ExpressionType.ConvertChecked)) mapped = u.Operand; if (mapped is not MemberExpression m || m.Expression != _projection.Parameters[0] || !SortableObjectFields.Contains(m.Member.Name)) return null; var contract = typeof(redb.Core.Models.Contracts.IRedbObject); return contract.GetProperty(m.Member.Name) ?? contract.GetInterfaces().Select(i => i.GetProperty(m.Member.Name)).FirstOrDefault(pi => pi != null); } public IRedbProjectedQueryable Take(int count) { // S-4: после in-memory операций Take применяется в памяти (_pagingOps), иначе сервер // отрежет страницу до фильтра; без них - прежний быстрый путь, LIMIT уходит в SQL. if (HasInMemoryOps) return WithPagingOp(isSkip: false, count); return new RedbProjectedQueryable( _sourceQuery.Take(count), _projection, _wherePredicates, _orderByExpressions, _projectedStructureIds, _projectedFieldPaths, _provider, _schemeId, _isDistinct, _pagingOps, sourcePaged: true, sourceOrdered: _sourceOrdered); } public IRedbProjectedQueryable Skip(int count) { if (HasInMemoryOps) return WithPagingOp(isSkip: true, count); return new RedbProjectedQueryable( _sourceQuery.Skip(count), _projection, _wherePredicates, _orderByExpressions, _projectedStructureIds, _projectedFieldPaths, _provider, _schemeId, _isDistinct, _pagingOps, sourcePaged: true, sourceOrdered: _sourceOrdered); } private bool HasInMemoryOps => _wherePredicates.Count > 0 || _orderByExpressions.Count > 0 || _isDistinct || _pagingOps.Count > 0; private RedbProjectedQueryable WithPagingOp(bool isSkip, int count) { var copy = new RedbProjectedQueryable( _sourceQuery, _projection, _wherePredicates, _orderByExpressions, _projectedStructureIds, _projectedFieldPaths, _provider, _schemeId, _isDistinct, _pagingOps, _sourcePaged, _sourceOrdered); copy._pagingOps.Add((isSkip, count)); return copy; } public IRedbProjectedQueryable Distinct() { // Distinct for projection is applied in memory after projection return new RedbProjectedQueryable( _sourceQuery, _projection, _wherePredicates, _orderByExpressions, _projectedStructureIds, _projectedFieldPaths, _provider, _schemeId, isDistinct: true, pagingOps: _pagingOps, sourcePaged: _sourcePaged, sourceOrdered: _sourceOrdered); } public async Task> ToListAsync(CancellationToken cancellationToken = default) { // S-7 (решение владельца 2026-09-03): Select с Agg.* маршрутизируется в аггрегатный путь - // одна строка агрегатов. Раньше пример из XML-доки Agg // (.Select(x => new { Total = Agg.Sum(...) })) бросал NotSupportedException из // скомпилированного маркера при материализации. if (_fieldExtractor.HasAggregations(_projection)) { var aggregated = await _sourceQuery.AggregateAsync(_projection); IEnumerable aggRows = [aggregated]; foreach (var aggWhere in _wherePredicates) aggRows = aggRows.Where(aggWhere.Compile()); return aggRows.ToList(); } // OPTIMIZATION: Load only required structure_ids if possible List> fullObjects; // LOG: Projection information // Extract text paths and structure_ids from projection if not yet extracted if (_projectedStructureIds == null && _fieldExtractor.ReadsNoPropsField(_projection)) { // Base fields only: no value row is read, so the scheme is not needed either. _projectedStructureIds = []; } else if (_projectedFieldPaths == null && _provider != null && _schemeId > 0) { // Extract text paths for SQL projection function (search_objects_with_projection_by_paths) _projectedFieldPaths = _fieldExtractor.ExtractFieldPathStrings(_projection); // Also extract structure_ids (used by Pro's ProLazyPropsLoader for filtered _values loading) var scheme = await _provider.GetSchemeAsync(_schemeId, cancellationToken: cancellationToken); if (scheme != null) { _projectedStructureIds = _fieldExtractor.ExtractStructureIds(scheme, _projection); } } // FIX: ALWAYS skip Props re-loading during projection. // // Projection flow is two-phase: // Phase 1 (SQL): search_objects_with_projection_by_paths returns JSON with // "properties" containing ONLY the projected fields. // Phase 2 (C#): Deserialization maps "properties" → Props via setter, // which sets _propsLoaded = true. Props is PARTIAL but sufficient. // Phase 3 (C#): compiledProjection(redbObj) extracts needed fields → TResult. // RedbObject is then discarded. // // Without skipProps=true, MaterializeResultsFromJson would: // - In EAGER mode: call LazyPropsLoader.LoadPropsForManyAsync which re-loads // the FULL object via get_object_json, OVERWRITING the partial Props from SQL // projection. This causes double DB round-trip and defeats the projection. // - In LAZY mode: set _lazyLoader + _propsLoaded=false, causing the lazy loader // to load full Props on first .Props access, again defeating projection. // // In both cases the final TResult is correct (projection extracts the right fields), // but the optimization is wasted — we load full object data anyway. // // The fix: tell MaterializeResultsFromJson to skip ALL Props post-processing. // Props data is already in the deserialized object from the SQL projection JSON. bool skipProps = true; // Try to use optimized loading via internal method if (_sourceQuery is RedbQueryable redbQueryable) { // The settings of the projection go into a copy: the source query stays as it was // and can be run again, as a list or under another projection. var working = redbQueryable.CloneForProjection(); // Set text paths in context BEFORE call // Context is read in PostgresQueryProvider to select SQL function working.SetProjectedFieldPaths(_projectedFieldPaths); fullObjects = await working.ToListWithProjectionAsync(_projectedStructureIds, skipProps, cancellationToken); } else { fullObjects = await _sourceQuery.ToListAsync(cancellationToken: cancellationToken); } // CRITICAL: Disable lazy loading BEFORE applying projection! // Data already loaded from SQL (search_objects_with_projection_by_paths), // result will be anonymous type — lazy loading not needed and dangerous. foreach (var obj in fullObjects) { obj._lazyLoader = null; // Ревью 2026-09-03: у объекта, в чьей ЧАСТИЧНОЙ выборке не нашлось ни одной строки // _values (все проецируемые поля null), Props приезжает null - а лямбда проекции // обязана исполниться. Внутри проекционного пути null-Props означает «пусто», а не // «не загружено»: RedbObject тут же выбрасывается, V4-семантика чтения не затронута. // Raw access: the getter of an object without loaded Props is a lazy load (or nothing, the loader is gone). if (obj.GetPropsDirectly() is null) obj.Props = new TProps(); } var compiledProjection = _projection.Compile(); // Apply projection to each object var projectedResults = fullObjects.Select(redbObj => compiledProjection(redbObj)); // Apply Where filters after projection foreach (var wherePredicate in _wherePredicates) { var compiledPredicate = wherePredicate.Compile(); projectedResults = projectedResults.Where(compiledPredicate); } // Apply OrderBy sorting after projection if (_orderByExpressions.Count > 0) { IOrderedEnumerable? orderedResults = null; // S-2 (ревью 2026-09-03): null-ключ раньше подменялся new object(), и Comparer // валил запрос ("does not implement IComparable"). Ключи сравниваются null-безопасно // с LINQ-семантикой: null меньше любого значения. var nullSafe = Comparer.Create(static (a, b) => a == null && b == null ? 0 : a == null ? -1 : b == null ? 1 : System.Collections.Comparer.Default.Compare(a, b)); for (int i = 0; i < _orderByExpressions.Count; i++) { var (keySelector, isDescending) = _orderByExpressions[i]; var compiledDelegate = ((LambdaExpression)keySelector).Compile(); Func key = item => compiledDelegate.DynamicInvoke(item); if (i == 0) orderedResults = isDescending ? projectedResults.OrderByDescending(key, nullSafe) : projectedResults.OrderBy(key, nullSafe); else orderedResults = isDescending ? orderedResults!.ThenByDescending(key, nullSafe) : orderedResults!.ThenBy(key, nullSafe); } if (orderedResults != null) projectedResults = orderedResults; } // Apply Distinct if flag is set if (_isDistinct) { projectedResults = projectedResults.Distinct(); } // S-4: Take/Skip, вызванные после in-memory операций, применяются здесь в порядке вызова. foreach (var (isSkip, n) in _pagingOps) projectedResults = isSkip ? projectedResults.Skip(n) : projectedResults.Take(n); return projectedResults.ToList(); } public async Task CountAsync(CancellationToken cancellationToken = default) { // S-3 (ревью 2026-09-03): Distinct применяется в памяти в ToListAsync - Count обязан // считать то же самое. Агрегатная проекция (S-7) тем же путём: всегда одна строка. if (_wherePredicates.Count > 0 || _isDistinct || _pagingOps.Count > 0 || _fieldExtractor.HasAggregations(_projection)) { var results = await ToListAsync(cancellationToken: cancellationToken); return results.Count; } // Otherwise count does not depend on the projection return await _sourceQuery.CountAsync(cancellationToken: cancellationToken); } public async Task FirstOrDefaultAsync(CancellationToken cancellationToken = default) { // For FirstOrDefault apply all operations and take first element var results = await ToListAsync(cancellationToken: cancellationToken); return results.FirstOrDefault(); } /// /// Get projection info: SQL function and structure_ids that will be loaded. /// public async Task GetProjectionInfoAsync(CancellationToken cancellationToken = default) { HashSet? structureIds = _projectedStructureIds; if (structureIds == null && _provider != null && _schemeId > 0) { var scheme = await _provider.GetSchemeAsync(_schemeId, cancellationToken: cancellationToken); if (scheme != null) { structureIds = _fieldExtractor.ExtractStructureIds(scheme, _projection); _projectedStructureIds = structureIds; } } if (structureIds == null) return "Full load"; return structureIds.Count > 0 ? $"Projection: {structureIds.Count} structure_ids" : "Projection: base fields only"; } }