RVN013 - Query result is not bounded by Take()
-
RVN013 reports RavenDB queries that materialize results with
ToList,ToArray,ToListAsync, orToArrayAsync,
or register lazy execution withLazilyorLazilyAsync, without an explicit result bound. -
Default severity: Info
Automated code fix: No -
In this article:
Description
RavenDB applies no default limit to query results.
When a query does not specify a page size, the server returns all matching results in a single call
(see Paging query results).
Without Take(n), the number of results depends on the data:
a query that returns a few documents against test data can return an entire collection in production,
and ToList or ToArray loads every result into memory.
Lazily() and LazilyAsync() register a query for later execution.
They delay execution but do not limit how many results the query retrieves when it runs.
By default, when a query returns more than 2048 results, the server raises a "Page size too big" performance hint.
Trigger condition
When is RVN013 reported?
RVN013 checks calls to ToList(), ToArray(), ToListAsync(), ToArrayAsync(), Lazily(), and LazilyAsync(),
with or without arguments, made on a RavenDB query.
The diagnostic highlights the method name, such as ToList or Lazily.
Query types checked:
-
LINQ queries:
queries that start fromsession.Query<T>(), in sync and async sessions,
including after standard LINQ operators such asOfType<T>(),Select, andGroupBy.
Queries written withfrom … select …and queries held in local variables are also checked. -
Document queries:
queries that start fromsession.Advanced.DocumentQuery<T>()orsession.Advanced.AsyncDocumentQuery<T>(). -
Raw queries:
queries that start fromsession.Advanced.RawQuery<T>(query)orsession.Advanced.AsyncRawQuery<T>(query),
when the RQL argument is a compile-time string constant that does not contain the wordlimit.
This includes constant interpolated strings, such as$"from Orders"or$"from {Collection}"whenCollectionis aconst string.
Where RVN013 looks for Take():
The call is reported when the query has no Take() call in any of these places:
- The method chain before the checked call, including the source of a query-syntax
fromclause,
such asfrom o in session.Query<Order>().Take(10) select o. - The initializer of a local variable that holds the query.
- An assignment to that local variable that appears before the checked call in the same method,
such asquery = query.Take(10);.
RVN013 treats any Take() call in one of these places as an explicit bound, including Take(int.MaxValue).
When is RVN013 not reported?
First,FirstOrDefault,Single,SingleOrDefault,Any,Count,LongCount, and their async forms.
They return a single result or value.- Raw queries whose RQL text contains the word
limit(case-insensitive),
or whose RQL argument is not a compile-time string constant, such as a nonconstant variable, a parameter,
a method result, or an interpolated string with a nonconstant hole. - LINQ over results already loaded into memory,
such as the secondToList()insession.Query<Order>().Take(10).ToList().Where(…).ToList().
How to resolve
- In LINQ queries and document queries, call
.Take(n)before the checked call. - In raw queries, add a
limitclause to the RQL. - To retrieve all results, page through them with
Skip()andTake(),
or stream them instead of loading them all into memory.
If the result set is known to be small,Take(int.MaxValue)states that retrieving all results is intentional.
Before (triggers RVN013)
var orders = session.Query<Order>()
.Where(x => x.Company == "companies/1-A")
// Triggers RVN013: no Take(), so every matching order is returned.
.ToList();
After (correct)
var orders = session.Query<Order>()
.Where(x => x.Company == "companies/1-A")
.Take(50)
.ToList();
Document queries and raw queries
// Document query: bounded by Take()
var orders = session.Advanced.DocumentQuery<Order>()
.WhereEquals(x => x.Company, "companies/1-A")
.Take(50)
.ToList();
// Raw query: bounded by a 'limit' clause in the RQL
var orders = session.Advanced
.RawQuery<Order>("from Orders where Company = $company limit 50")
.AddParameter("company", "companies/1-A")
.ToList();
Retrieving all results
var query = session.Query<Order>()
.Where(x => x.Company == "companies/1-A");
// Stream the results: each result is read from the stream one at a time.
using var stream = session.Advanced.Stream(query);
while (stream.MoveNext())
{
Order order = stream.Current.Document;
// Process the order...
}
// The result set is known to be small: state that retrieving all results is intentional.
var orders = session.Query<Order>()
.Where(x => x.Company == "companies/1-A")
.Take(int.MaxValue)
.ToList();
Limitations
-
Only
ToList,ToArray,ToListAsync,ToArrayAsync,Lazily, andLazilyAsyncare checked.
Other ways to retrieve all results, such as iterating the query in aforeachloop,
ToDictionary, orAsEnumerable().ToList(), are not reported. -
A
Take()applied outside the method is not detected.
A query typed asIRavenQueryable<T>,IDocumentQuery<T>, or another RavenDB query type is reported when it is received as a parameter, read from a field or property, or returned by a method, even if it was bounded where it was created.A query typed as
IQueryable<T>is followed only through local-variable initializers;
as a parameter, field, or property, it is not checked. -
Conditions are not evaluated.
An earlier assignment containingTake()inside anifblock suppresses RVN013 even if the block does not run,
while aTake()inside a conditional expression, such asflag ? query.Take(10) : query, is not detected. -
In raw queries,
limitis matched anywhere in the RQL text,
so a query that useslimitonly as a field name or inside a string value is not reported.Nonconstant interpolated RQL is not checked, even when only a filter value is interpolated.
For example,$"from Orders where Company = '{company}'"is not reported whencompanyis a nonconstant variable.
Related C# analyzers
-
RVN012
Reports independent loads and materializing queries on the same session that can be sent in a single request using the lazy API.Its code fix converts queries to
Lazily()orLazilyAsync(). RVN013 checks these calls too, so an unbounded query is still reported at theLazilyorLazilyAsyncmethod name.Add
Take()before the lazy registration to resolve it.