Skip to content

[9.0] LINQ: index into document arrays in OrderBy, Select and jagged Where (backport of #5953) - #5956

Merged
jeremydmiller merged 6 commits into
9.0from
fix/5949-document-array-indexing-9.0
Nov 15, 2026
Merged

jeremydmiller merged 6 commits into
9.0from
fix/5949-document-array-indexing-9.0

Conversation

@jeremydmiller

@jeremydmiller jeremydmiller commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

Merge after #5948. This branch is stacked on #5948, the 9.0 backport of #5943, so until that merges the diff here also shows its commit (a2967fe9e). The #5949 change is 78f67af6b, plus a886a6ad7, which switches the new migration note to the asterisk bullets the 9.0 guide uses (markdownlint MD004).

Backport of #5953 to 9.0. Fixes #5949 on 9.x.

Cherry-picked with -x from 6d2c14e05. The 9.0 adaptations:

  • BadLinqExpressionException is Marten.Exceptions.BadLinqExpressionException on 9.0.
  • 9.0 has no union members, so that using is dropped in WhereClauseParser.
  • The migration note goes under 9.60.0.

CI (started by hand): https://github.com/JasperFx/marten/actions/runs/43758805993 (head 80b3e0cc6). The stack merges current origin/9.0 (through #5956), which brings in #5951 (HiLo mt_get_next_hi) and #5980 (a docs-only change). With those merged in, the top of the chain (#5971) passes full LinqTests net10.0 (3036/3036) and DocumentDbTests' Writing.Identity.Sequences namespace (33/33). #5956 also carries the one-line isComputedProjection fix that keeps an array index in a top-level Select() on the select visitor.

Root cause

An index into an array or list on the document translated in only one place: a Where() comparison with a single index, through SimpleExpression. Everywhere else it failed:

Query Before Why
OrderBy(x => x.Values[1]) Invalid OrderBy() expression Ordering resolves through MemberFinder, which records ArrayIndex as an invalid node. A List<T> indexer or x.Children[0].Name silently lost its index, so the query ordered by the wrong value.
Select(x => x.Values[1]) ArgumentNullException ('array') SelectorVisitor let ExpressionVisitor visit the index's children, which return null, and then rebuild the ArrayIndex node from them.
Where(x => x.Grid[1][0] == 4) ArgumentNullException ('array') SimpleExpression rebuilt the inner index the same way. Past that, ChildDocumentAtIndex (the element x.Grid[1]) could not be indexed again.
Select(x => new { C = x.Grid[1][0] }) wrong value SelectParser resolved only x.Grid[1] and re-applied the outer index, so it read x.Grid[0].
Where(x => x.Flags[1]) with bool[] Flags exception No bool[] / List<bool> on a document could be resolved at all. BooleanMember read the member type of the collection's ElementMember, which has none.

The fix

  • ChildDocumentAtIndex can now index an element that is itself an array.
    • A scalar inner element uses the same SimpleCastMember / StringMember factories value collections use (now ForIndexedElement), on the element's own jsonb locator: CAST(d.data -> 'grid' -> 1 ->> 0 as integer).
    • A complex inner element becomes another ChildDocumentAtIndex, so x.ChildGrid[1][0].Score and three-deep indexes work.
    • It now has a MemberType, so Select(x => x.Children[0]) and Select(x => x.Grid[1]) deserialize the element.
  • One resolution path for indexes. New helpers HasElementIndex() and MemberForIndexedChain() route any member chain that contains an array index, a List<T> indexer or ElementAt() through the SimpleExpression walk that Where() comparisons already use. That walk now visits only the array side of an index rather than rebuilding the node. The callers are:
    • Ordering (OrderBy/ThenBy)
    • SelectorVisitor (scalar Select, including a List<T> indexer and ElementAt)
    • SelectParser (anonymous types and records)
    • WhereClauseParser (bare bool elements, such as Where(x => x.Flags[1]))
  • Unaffected SQL is unchanged. A chain without an index resolves exactly as before. A throwaway test dumped the SQL for 45 unaffected shapes (where/order/select over members, nested members, single indexes, dictionaries, Any/Contains/Count/Length, ToLower, case-insensitive ordering, anonymous types, records, Distinct). The SQL is byte-identical on the base and on this branch.
  • Behaviour change: a negative index throws BadLinqExpressionException. It used to become a negative jsonb index, which PostgreSQL reads from the end of the array, so x.Values[-1] == 3 silently compared the last element.
  • An index past the end reads as null, as it always did in Where(). A comparison against it does not match, it sorts last ascending, and a Select returns null or default. This is documented and tested.
  • bool collections can now be queried, and Any(f => f) over one registers a filter instead of throwing NullReferenceException.
  • Case-insensitive ordering of an indexed string now lowers the real locator, not the placeholder the constructor built.
  • Docs: a new section, "Reading an Element by Position", in child-collections.md, and a 9.60.0 migration note. markdownlint and cspell report 0 issues.

Tests

Bug_5949_indexing_document_arrays has 81 cases, each checked against LINQ to Objects over the same six documents.

  • Index forms: literal indexes and captured-local indexes.
  • Collection shapes: int[], List<int>, ElementAt, string[], List<string>, bool[], double[], int[][], List<List<int>>, string[][], int[][][], and members of indexed child documents (Children[1].Score, ChildList[0].Name, ChildGrid[1][0].Score).
  • Where: comparisons, two indexes compared with each other, &&/||/!, bare bool elements, and Contains/Any over a bool[].
  • OrderBy: ascending and descending for every shape, plus ThenByDescending on an index.
  • Select: scalar, a whole child element, a jagged row, an anonymous type and a record.
  • Edge cases: past-the-end indexes in Where, OrderBy and Select, and negative-index refusal in Where, OrderBy and Select.

Red, then green on 9.0 (net10.0, marten_9_y)

markdownlint over docs/ reports 0 issues on this branch, as it does on 9.0. cspell reports 0.

Full suite on this branch

  • LinqTests net10.0 against marten_9_y: 2230 / 2230

No CollectionUsage / SelectMany code is touched.

🤖 Generated with Claude Code

jeremydmiller and others added 2 commits November 15, 2026 11:54
…ixes #5949)

An index into an array or list on the document translated only in a Where()
comparison with a single index. OrderBy(x => x.Values[1]) was refused
("Invalid OrderBy() expression": MemberFinder treats ArrayIndex as
invalid), Select(x => x.Values[1]) threw ArgumentNullException ('array')
because SelectorVisitor rebuilt the index node from null children, and a
jagged x.Grid[1][0] failed everywhere: SimpleExpression rebuilt the inner
index node the same way, and ChildDocumentAtIndex could not index again.

- ChildDocumentAtIndex indexes an element that is itself an array: a scalar
  element through the same SimpleCastMember/StringMember factories value
  collections use, a complex one as another ChildDocumentAtIndex.
- OrderBy/ThenBy, Select (scalar, anonymous type, record) and bool
  predicates resolve a chain containing an index through the SimpleExpression
  walk Where() comparisons already used. Chains without an index resolve
  exactly as before; the SQL for 45 such shapes is byte-identical.
- A negative index throws BadLinqExpressionException instead of becoming a
  negative jsonb index, which PostgreSQL reads from the end of the array.
- A bool[] / List<bool> on the document could not be resolved at all
  (BooleanMember read the member type of an ElementMember); it can now, and
  Any(f => f) over one registers a filter instead of throwing.
- An indexed string element's case-insensitive ordering lowers the real
  locator, not the placeholder the constructor built.

Docs: "Reading an Element by Position" in child-collections.md, and a
migration note for the negative-index behavior change (under 9.60.0 on 9.0).

9.0 adaptation: BadLinqExpressionException is Marten.Exceptions on 9.0 (no
union members either), and the migration note goes under 9.60.0.

(cherry picked from commit 6d2c14e)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jeremydmiller and others added 3 commits November 15, 2026 13:04
…y-indexing-9.0

# Conflicts:
#	docs/migration-guide.md
…5949 x #5942)

#5942 (merged on 9.0 as #5954) sends a top-level projection it classifies as
computed through the scalar translator and refuses it when that fails. Every
BinaryExpression counted as computed, which took in #5949's array indexes:
Select(x => x.Values[1]), Select(x => x.Grid[1][0]) and Select(x => x.Grid[1])
were refused instead of reaching the select visitor that translates them.
An ArrayIndex is now not a computed projection; arithmetic over one still is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jeremydmiller
jeremydmiller merged commit 4002146 into 9.0 Nov 15, 2026
31 checks passed
@jeremydmiller
jeremydmiller deleted the fix/5949-document-array-indexing-9.0 branch November 15, 2026 20:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant