QueryBuilder
public struct QueryBuilder<T> : Sendable where T : Decodable, T : Encodable, T : Sendable
An immutable, fluent query builder for executing typed queries against a NyaruDB collection.
QueryBuilder is created by NyaruCollection.find() and provides a
chainable API for adding predicates, sorting, pagination, and executing
the query:
let results = try await collection.find()
.where("age", isGreaterThan: 18)
.where("status", isEqualTo: "active")
.sort(by: "name", ascending: true)
.limit(20)
.offset(0)
.execute()
Query planning. The builder includes a simple cost-based planner that selects the most efficient access path:
- Index equality lookup (highest priority).
- Index
INset lookup. - Index range/comparison lookup.
- Partition scan (if a partition key equality predicate exists).
- Full collection scan (fallback).
Call explain() to inspect the plan without executing.
-
Adds an equality predicate:
field == value.Declaration
Swift
public func `where`(_ field: String, isEqualTo value: FieldValueConvertible) -> QueryBuilder<T>Parameters
fieldThe field name.
valueThe expected value.
Return Value
A new query builder with the predicate added.
-
Adds a not-equal predicate:
field != value.Declaration
Swift
public func `where`(_ field: String, isNotEqualTo value: FieldValueConvertible) -> QueryBuilder<T> -
Adds a less-than predicate:
field < value.Declaration
Swift
public func `where`(_ field: String, isLessThan value: FieldValueConvertible) -> QueryBuilder<T> -
Adds a less-than-or-equal predicate:
field <= value.Declaration
Swift
public func `where`(_ field: String, isLessThanOrEqualTo value: FieldValueConvertible) -> QueryBuilder<T> -
Adds a greater-than predicate:
field > value.Declaration
Swift
public func `where`(_ field: String, isGreaterThan value: FieldValueConvertible) -> QueryBuilder<T> -
Adds a greater-than-or-equal predicate:
field >= value.Declaration
Swift
public func `where`(_ field: String, isGreaterThanOrEqualTo value: FieldValueConvertible) -> QueryBuilder<T> -
Adds an inclusive range predicate:
lower <= field <= upper.Declaration
Swift
public func `where`( _ field: String, isBetween lower: FieldValueConvertible, and upper: FieldValueConvertible ) -> SelfParameters
fieldThe field name.
lowerThe lower bound.
upperThe upper bound.
-
Adds a membership predicate:
field IN values.Declaration
Swift
public func `where`(_ field: String, isIn values: [FieldValueConvertible]) -> QueryBuilder<T> -
Adds a negated membership predicate:
field NOT IN values.Declaration
Swift
public func `where`(_ field: String, isNotIn values: [FieldValueConvertible]) -> QueryBuilder<T> -
Adds a substring containment predicate on a string field.
Declaration
Swift
public func `where`(_ field: String, contains substring: String) -> QueryBuilder<T> -
Adds a string prefix predicate.
Declaration
Swift
public func `where`(_ field: String, startsWith prefix: String) -> QueryBuilder<T> -
Adds a string suffix predicate.
Declaration
Swift
public func `where`(_ field: String, endsWith suffix: String) -> QueryBuilder<T> -
Adds a SQL-style LIKE predicate. The pattern supports
%(any sequence) and_(single character). Matching is case-insensitive.Declaration
Swift
public func `where`(_ field: String, like pattern: String) -> QueryBuilder<T>Parameters
patternThe LIKE pattern.
-
Adds a shell-style glob predicate. The pattern supports
*(any sequence),?(single character), and[...](character class). Matching is case-sensitive.Declaration
Swift
public func `where`(_ field: String, glob pattern: String) -> QueryBuilder<T>Parameters
patternThe glob pattern.
-
Requires that the given field is present (not null/absent).
Declaration
Swift
public func whereExists(_ field: String) -> QueryBuilder<T> -
Requires that the given field is absent (null or missing).
Declaration
Swift
public func whereNotExists(_ field: String) -> QueryBuilder<T> -
Adds an arbitrary predicate node to the conjunction.
Declaration
Swift
public func `where`(_ predicate: Predicate) -> QueryBuilder<T> -
Sets the sort field and direction for the query results.
Sorting is performed in memory after fetching matching documents. When a sort field is set, pagination (offset/limit) is applied after sorting.
Declaration
Swift
public func sort(by field: String, ascending: Bool = true) -> QueryBuilder<T>Parameters
fieldThe field to sort by.
ascendingtruefor ascending order (default),falsefor descending.Return Value
A new query builder with sort applied.
-
Limits the number of results returned.
Declaration
Swift
public func limit(_ count: Int) -> QueryBuilder<T>Parameters
countMaximum number of documents to return (0 means none).
Return Value
A new query builder with the limit applied.
-
Skips the first
countresults.Pagination (offset) requires a sort field to guarantee deterministic ordering. Throws
unsupportedOperationif offset is set without a sort field.Declaration
Swift
public func offset(_ count: Int) -> QueryBuilder<T>Parameters
countNumber of results to skip.
Return Value
A new query builder with the offset applied.
-
explain()AsynchronousReturns the query execution plan without running the query.
Use this to inspect how the query will be executed and which access path the planner selected. The planner uses a fixed priority order (index equality > IN set > range > partition scan > full scan) and reports how many top-level predicates remain as residual memory filters.
Declaration
Swift
public func explain() async -> QueryPlanReturn Value
A
QueryPlandescribing the strategy and residual predicates.
-
execute()AsynchronousExecutes the query and returns all matching documents, decoded.
Throws
NyaruError.decodingFailedif a document fails to decode.Declaration
Swift
public func execute() async throws -> [T]Return Value
An array of decoded documents matching all predicates.
-
first()AsynchronousReturns the first matching document, or
nilif none match.Internally applies
limit(1)before executing.Declaration
Swift
public func first() async throws -> T? -
count()AsynchronousReturns the count of matching documents without decoding them.
More efficient than
execute().countbecause it skips decoding. When the query is fully covered by an index, the count is answered from the pointer list alone — no disk I/O at all.Declaration
Swift
public func count() async throws -> Int -
distinctValues(on:Asynchronous) Returns all distinct values of a field among the matching documents.
Declaration
Swift
public func distinctValues(on field: String) async throws -> [FieldValue]Parameters
fieldThe field to collect distinct values from.
Return Value
An array of distinct
FieldValueinstances. -
delete()AsynchronousDeletes all matching documents and returns the number removed.
The matched documents were already parsed to evaluate the predicates, so their index keys are extracted here for free and handed to the core — no document is read from disk a second time.
Throws
Errors from the underlying delete operation.Declaration
Swift
@discardableResult public func delete() async throws -> IntReturn Value
The count of deleted documents.
View on GitHub