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:

  1. Index equality lookup (highest priority).
  2. Index IN set lookup.
  3. Index range/comparison lookup.
  4. Partition scan (if a partition key equality predicate exists).
  5. Full collection scan (fallback).

Call explain() to inspect the plan without executing.

Fluent predicate API

  • Adds an equality predicate: field == value.

    Declaration

    Swift

    public func `where`(_ field: String, isEqualTo value: FieldValueConvertible) -> QueryBuilder<T>

    Parameters

    field

    The field name.

    value

    The 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
    ) -> Self

    Parameters

    field

    The field name.

    lower

    The lower bound.

    upper

    The 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

    pattern

    The 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

    pattern

    The 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

    field

    The field to sort by.

    ascending

    true for ascending order (default), false for 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

    count

    Maximum number of documents to return (0 means none).

    Return Value

    A new query builder with the limit applied.

  • Skips the first count results.

    Pagination (offset) requires a sort field to guarantee deterministic ordering. Throws unsupportedOperation if offset is set without a sort field.

    Declaration

    Swift

    public func offset(_ count: Int) -> QueryBuilder<T>

    Parameters

    count

    Number of results to skip.

    Return Value

    A new query builder with the offset applied.

Planning

  • explain() Asynchronous

    Returns 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 -> QueryPlan

    Return Value

    A QueryPlan describing the strategy and residual predicates.

Execution

  • execute() Asynchronous

    Executes the query and returns all matching documents, decoded.

    Throws

    NyaruError.decodingFailed if a document fails to decode.

    Declaration

    Swift

    public func execute() async throws -> [T]

    Return Value

    An array of decoded documents matching all predicates.

  • first() Asynchronous

    Returns the first matching document, or nil if none match.

    Internally applies limit(1) before executing.

    Declaration

    Swift

    public func first() async throws -> T?
  • count() Asynchronous

    Returns the count of matching documents without decoding them.

    More efficient than execute().count because 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

    field

    The field to collect distinct values from.

    Return Value

    An array of distinct FieldValue instances.

  • delete() Asynchronous

    Deletes 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 -> Int

    Return Value

    The count of deleted documents.