arcadedb_protocol/client/results.rs
1//! Query result shapes — the owned [`QueryResult`] wrapper, the streaming
2//! [`StreamSummary`], and the `StreamQuery` batch consumer.
3
4use super::*;
5
6/// One batch of streamed query results — the raw `QueryResult` proto
7/// message, aliased to avoid clashing with the owned [`QueryResult`]
8/// wrapper. Carries `records`, `total_records_in_batch`,
9/// `running_total_emitted`, and `is_last_batch`.
10pub use crate::proto::com::arcadedb::grpc::QueryResult as QueryResultBatch;
11
12/// The result of a SQL query, bundling the returned records with server-side
13/// execution timing.
14#[derive(Debug)]
15pub struct QueryResult {
16 /// Record rows returned by the query.
17 pub records: Vec<GrpcRecord>,
18 /// Server-reported execution time in milliseconds.
19 pub execution_time_ms: i64,
20}
21
22impl QueryResult {
23 /// Number of records in the result set.
24 pub fn len(&self) -> usize {
25 self.records.len()
26 }
27
28 /// Whether the result set is empty.
29 pub fn is_empty(&self) -> bool {
30 self.records.is_empty()
31 }
32
33 /// Iterate over the records.
34 pub fn iter(&self) -> Iter<'_, GrpcRecord> {
35 self.records.iter()
36 }
37
38 /// Lazy, borrowing typed decode: each record → `T` on demand, with no
39 /// per-row promotion to owned (string/blob views borrow from this
40 /// result — consume rows within its scope, which the iterator's lifetime
41 /// enforces). The method form of `records.iter().map(T::try_from)`.
42 ///
43 /// A decode failure surfaces as an `Err` item mid-iteration (mirroring
44 /// the streaming path) rather than failing the whole call up front;
45 /// collect into `Result<Vec<_>, _>` for fail-fast when ownership of all
46 /// rows is wanted anyway.
47 pub fn rows<'r, T>(&'r self) -> impl Iterator<Item = Result<T, RecordDecodeError>> + 'r
48 where
49 T: TryFrom<&'r GrpcRecord, Error = RecordDecodeError> + 'r,
50 {
51 self.records.iter().map(T::try_from)
52 }
53
54 /// Typed decode of the first row, `None` when the result is empty — the
55 /// `fetch_optional` shape for callers that already hold a
56 /// [`QueryResult`]. A decode failure surfaces as `Err` (the row existed
57 /// but did not match `T`), the empty result as `Ok(None)`.
58 pub fn first<T>(&self) -> std::result::Result<Option<T>, RecordDecodeError>
59 where
60 T: for<'r> TryFrom<&'r GrpcRecord, Error = RecordDecodeError>,
61 {
62 self.records.first().map(T::try_from).transpose()
63 }
64
65 /// Typed decode of the first row, with an empty result set an
66 /// [`ArcadeDbError::NotFound`] — the one-row contract without repeating
67 /// `records.into_iter().next()` + hand-rolled error at every call site.
68 pub fn one<T>(&self) -> Result<T>
69 where
70 T: for<'r> TryFrom<&'r GrpcRecord, Error = RecordDecodeError>,
71 {
72 self.first()
73 .map_err(|e| ArcadeDbError::Decode {
74 what: "first row".into(),
75 source: e,
76 })?
77 .ok_or_else(|| ArcadeDbError::NotFound {
78 operation: "query".into(),
79 detail: "result set was empty".into(),
80 })
81 }
82
83 /// Eager parallel decode of the whole result set (requires the `rayon`
84 /// feature): `rows().collect()` semantics on the global rayon pool,
85 /// with one contract difference — this is a collect, not an iterator,
86 /// so the first `Err` short-circuits (after in-flight items drain).
87 ///
88 /// Below `par_min_records()` the sequential path runs instead: task
89 /// overhead would eat the gain on point lookups and small candidate
90 /// lists, and opting into the feature should never regress them.
91 #[cfg(feature = "rayon")]
92 pub fn par_rows<T>(&self) -> Result<Vec<T>, RecordDecodeError>
93 where
94 T: for<'r> TryFrom<&'r GrpcRecord, Error = RecordDecodeError> + Send,
95 {
96 use rayon::prelude::*;
97 if self.records.len() < par_min_records() {
98 return self.records.iter().map(T::try_from).collect();
99 }
100 self.records
101 .par_iter()
102 .map(T::try_from)
103 .collect::<Result<Vec<_>, _>>()
104 }
105
106 /// Eager typed decode of the whole result set — `rows().collect()` as a
107 /// single call; the first `Err` short-circuits.
108 pub fn rows_all<T>(&self) -> std::result::Result<Vec<T>, RecordDecodeError>
109 where
110 T: for<'r> TryFrom<&'r GrpcRecord, Error = RecordDecodeError>,
111 {
112 self.records.iter().map(T::try_from).collect()
113 }
114}
115
116/// Compiled-in default for the parallel-path batch threshold; override at
117/// runtime via `ARCADEDB_PAR_MIN_RECORDS` (see [`par_min_records`]) — the
118/// right number depends on row width, wide rows pay off earlier.
119#[cfg(feature = "rayon")]
120pub const DEFAULT_PAR_MIN_RECORDS: usize = 512;
121
122/// Effective parallel-path batch threshold, resolved once. Env override:
123/// `ARCADEDB_PAR_MIN_RECORDS=<n>` (invalid/zero values fall back to the
124/// compiled default).
125#[cfg(feature = "rayon")]
126pub fn par_min_records() -> usize {
127 static OVERRIDE: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
128 *OVERRIDE.get_or_init(|| {
129 std::env::var("ARCADEDB_PAR_MIN_RECORDS")
130 .ok()
131 .and_then(|v| v.parse().ok())
132 .filter(|n| *n > 0)
133 .unwrap_or(DEFAULT_PAR_MIN_RECORDS)
134 })
135}
136
137impl Deref for QueryResult {
138 type Target = Vec<GrpcRecord>;
139
140 fn deref(&self) -> &Self::Target {
141 &self.records
142 }
143}
144
145impl IntoIterator for QueryResult {
146 type Item = GrpcRecord;
147 type IntoIter = IntoIter<GrpcRecord>;
148
149 fn into_iter(self) -> Self::IntoIter {
150 self.records.into_iter()
151 }
152}
153
154/// Accounting for a consumed `StreamQuery` stream.
155#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
156pub struct StreamSummary {
157 /// Batches consumed before completion or early exit.
158 pub batches: u32,
159 /// Total records across the consumed batches.
160 pub rows: usize,
161 /// Server-side running total from the last consumed batch.
162 pub running_total_emitted: i64,
163 /// Whether the last consumed batch was flagged final by the server.
164 pub is_last_batch: bool,
165 /// Whether consumption stopped early via `ControlFlow::Break` — the
166 /// stream was dropped, cancelling the RPC (h2 cancel), and the server
167 /// may have more batches it never sent.
168 pub truncated: bool,
169}