Skip to main content

arcadedb_protocol/client/
query.rs

1//! Reads — plain and bound queries, rid/key lookups, one-row conveniences,
2//! and the returning-write helpers.
3
4use super::*;
5
6impl ArcadeDbClient {
7    /// Execute a SQL query and return the result records with server-side timing.
8    pub async fn query(&self, database: &str, query: &str) -> Result<QueryResult> {
9        let req = tonic::Request::new(ExecuteQueryRequest {
10            database: database.into(),
11            query: query.into(),
12            credentials: Some(self.auth.creds.clone()),
13            language: "sql".into(),
14            ..Default::default()
15        });
16
17        let resp = self
18            .data
19            .clone()
20            .execute_query(self.add_auth_headers(req))
21            .await
22            .map_err(|e| map_rpc_error("query", query, e))?
23            .into_inner();
24
25        let mut records = Vec::with_capacity(resp.results.iter().map(|qr| qr.records.len()).sum());
26        records.extend(resp.results.into_iter().flat_map(|qr| qr.records));
27
28        tracing::info!(
29            count = records.len(),
30            time_ms = resp.execution_time_ms,
31            query = %query,
32            "query results"
33        );
34
35        Ok(QueryResult {
36            records,
37            execution_time_ms: resp.execution_time_ms,
38        })
39    }
40
41    /// Execute a SQL query with bound parameters (the `:name` placeholders in
42    /// the query are filled from `parameters`).
43    ///
44    /// Prefer this over [`query`](Self::query) whenever the query references
45    /// caller-supplied values — bound params avoid SQL-injection concerns and
46    /// let ArcadeDB cache the parsed query plan. The vector-search operators
47    /// (`vector.sparseNeighbors`, `vector.fuse`, `SEARCH_INDEX`) in particular
48    /// expect array-valued params for the query token/weight vectors.
49    ///
50    /// Build parameter values with [`Params`](crate::Params) (e.g. the
51    /// [`params!`](crate::params!) macro), or assemble list/map values
52    /// directly from the proto types re-exported at the crate root.
53    pub async fn query_with_values(
54        &self,
55        database: &str,
56        query: &str,
57        parameters: impl Into<crate::encode::Params>,
58    ) -> Result<QueryResult> {
59        let parameters = parameters.into();
60        let req = tonic::Request::new(ExecuteQueryRequest {
61            database: database.into(),
62            query: query.into(),
63            parameters: parameters.0,
64            credentials: Some(self.auth.creds.clone()),
65            language: "sql".into(),
66            ..Default::default()
67        });
68
69        let resp = self
70            .data
71            .clone()
72            .execute_query(self.add_auth_headers(req))
73            .await
74            .map_err(|e| map_rpc_error("query", query, e))?
75            .into_inner();
76
77        let mut records = Vec::with_capacity(resp.results.iter().map(|qr| qr.records.len()).sum());
78        records.extend(resp.results.into_iter().flat_map(|qr| qr.records));
79
80        tracing::info!(
81            count = records.len(),
82            time_ms = resp.execution_time_ms,
83            query = %query,
84            "query results"
85        );
86
87        Ok(QueryResult {
88            records,
89            execution_time_ms: resp.execution_time_ms,
90        })
91    }
92
93    /// Fetch one record by rid — the O(1) path: direct bucket/position
94    /// dereference, no SQL parsing, no index traversal. The fastest read
95    /// ArcadeDB offers; prefer it whenever the caller already holds the
96    /// record's [`Link`](crate::Link) (a prior query's `@rid`, an edge's `@in`/`@out` —
97    /// all record intrinsics).
98    ///
99    /// Durability note: rids are stable for a database's *lifetime* but may
100    /// shift across rebuilds/backup-restores — treat them as within-lifetime
101    /// handles, never as persisted identifiers. Domain keys (e.g. a UNIQUE
102    /// index column) remain the durable identity.
103    pub async fn lookup_by_rid(
104        &self,
105        database: &str,
106        rid: &crate::Link,
107    ) -> Result<Option<GrpcRecord>> {
108        let req = LookupByRidRequest {
109            database: database.into(),
110            credentials: Some(self.auth.creds.clone()),
111            rid: rid.to_rid_string(),
112            transaction: None,
113        };
114        let resp = self
115            .data
116            .clone()
117            .lookup_by_rid(self.add_auth_headers(tonic::Request::new(req)))
118            .await
119            .map_err(|e| map_rpc_error("lookup by rid", &rid.to_string(), e))?
120            .into_inner();
121        Ok(resp.found.then_some(resp.record.unwrap_or_default()))
122    }
123
124    /// [`lookup_by_rid`](Self::lookup_by_rid) decoded into an owned DTO
125    /// (`T: TryFrom<&GrpcRecord>`, i.e. an owned `RecordDecode` struct).
126    pub async fn lookup<T>(&self, database: &str, rid: &crate::Link) -> Result<Option<T>>
127    where
128        T: for<'a> ::core::convert::TryFrom<
129            &'a GrpcRecord,
130            Error = crate::record::RecordDecodeError,
131        >,
132    {
133        match self.lookup_by_rid(database, rid).await? {
134            Some(rec) => {
135                let decoded = T::try_from(&rec).map_err(|e| ArcadeDbError::Decode {
136                    what: format!("lookup record {rid}"),
137                    source: e,
138                })?;
139                Ok(Some(decoded))
140            }
141            None => Ok(None),
142        }
143    }
144
145    // ------------------------------------------------------------------
146    // One-row conveniences + returning-write helpers. Each collapses a
147    // repeated call-site template.
148    // ------------------------------------------------------------------
149
150    /// Typed fetch of at most one row: `Ok(None)` on an empty result, a
151    /// decode error only when a row exists but does not match `T`.
152    ///
153    /// **Pair point-lookups with `LIMIT 1`** — the call decodes the first
154    /// row but the RPC still materializes the whole result set.
155    pub async fn fetch_optional<T>(
156        &self,
157        database: &str,
158        query: &str,
159        parameters: impl Into<crate::encode::Params>,
160    ) -> Result<Option<T>>
161    where
162        T: for<'r> TryFrom<&'r GrpcRecord, Error = RecordDecodeError>,
163    {
164        let res = self.query_with_values(database, query, parameters).await?;
165        match res.records.first() {
166            None => Ok(None),
167            Some(rec) => T::try_from(rec)
168                .map(Some)
169                .map_err(|e| ArcadeDbError::Decode {
170                    what: format!("fetch row of `{query}`"),
171                    source: e,
172                }),
173        }
174    }
175
176    /// [`fetch_optional`](Self::fetch_optional) with a one-row contract: an
177    /// empty result is [`ArcadeDbError::NotFound`], not `Ok(None)`.
178    ///
179    /// Same wire-cost note: keep the query itself to one row (`LIMIT 1`)
180    /// so the RPC materializes only what is decoded.
181    pub async fn fetch_one<T>(
182        &self,
183        database: &str,
184        query: &str,
185        parameters: impl Into<crate::encode::Params>,
186    ) -> Result<T>
187    where
188        T: for<'r> TryFrom<&'r GrpcRecord, Error = RecordDecodeError>,
189    {
190        self.fetch_optional(database, query, parameters)
191            .await?
192            .ok_or_else(|| ArcadeDbError::NotFound {
193                operation: "fetch_one".into(),
194                detail: query.into(),
195            })
196    }
197
198    /// Decode the single column of a single-row query (`SELECT count(*)`,
199    /// `SELECT max(x)`, …). `Ok(None)` when the query returned no row.
200    ///
201    /// The column is identified by position: the row must carry exactly one
202    /// property (a defensive guard — the proto row is a map, so "first
203    /// column" is only well-defined for one-column rows), decoded via
204    /// [`FromGrpcValue`](crate::record::FromGrpcValue). Aggregate queries
205    /// return a single row anyway (`SELECT count(*)`); anything wide
206    /// belongs in [`fetch_optional`](Self::fetch_optional).
207    pub async fn query_scalar<T>(
208        &self,
209        database: &str,
210        query: &str,
211        parameters: impl Into<crate::encode::Params>,
212    ) -> Result<Option<T>>
213    where
214        T: for<'de> crate::record::FromGrpcValue<'de>,
215    {
216        let res = self.query_with_values(database, query, parameters).await?;
217        match res.records.into_iter().next() {
218            None => Ok(None),
219            Some(rec) => {
220                let value = single_column_value(&rec, query)?;
221                T::from_grpc_value(value)
222                    .map(Some)
223                    .map_err(|e| ArcadeDbError::Decode {
224                        what: format!("query scalar of `{query}`"),
225                        source: e,
226                    })
227            }
228        }
229    }
230
231    /// Run a write command that returns the stored row and decode it. The
232    /// command must be a form whose response carries records:
233    ///
234    /// - `INSERT INTO t SET …` — returns the stored record as-is (the RPC
235    ///   runs with `return_rows = true`; no `RETURN` clause exists for
236    ///   INSERT — trailing `… RETURN AFTER` is a syntax error).
237    /// - `UPDATE t SET … RETURN AFTER WHERE …` — `RETURN BEFORE|AFTER` sits
238    ///   **between the SET/UPSERT part and WHERE**, not at statement end.
239    ///   The `UPSERT` variant additionally requires the WHERE column to
240    ///   carry an index.
241    ///
242    /// `Ok(None)` when the statement matched nothing (`RETURN AFTER` on a
243    /// zero-row UPDATE); use [`upsert_returning`](Self::upsert_returning)
244    /// for the strict one-row contract.
245    ///
246    /// Replaces the execute→extract→decode template at every returning-write
247    /// call site.
248    pub async fn write_returning_optional<T>(
249        &self,
250        database: &str,
251        command: &str,
252        parameters: impl Into<crate::encode::Params>,
253    ) -> Result<Option<T>>
254    where
255        T: for<'r> TryFrom<&'r GrpcRecord, Error = RecordDecodeError>,
256    {
257        let resp = self
258            .execute_with_values(database, command, parameters)
259            .await?;
260        match resp.records.first() {
261            None => Ok(None),
262            Some(rec) => T::try_from(rec)
263                .map(Some)
264                .map_err(|e| ArcadeDbError::Decode {
265                    what: format!("decode returning row of `{command}`"),
266                    source: e,
267                }),
268        }
269    }
270
271    /// [`write_returning_optional`](Self::write_returning_optional) with a
272    /// one-row contract (empty result → [`ArcadeDbError::NotFound`]).
273    pub async fn upsert_returning<T>(
274        &self,
275        database: &str,
276        command: &str,
277        parameters: impl Into<crate::encode::Params>,
278    ) -> Result<T>
279    where
280        T: for<'r> TryFrom<&'r GrpcRecord, Error = RecordDecodeError>,
281    {
282        self.write_returning_optional(database, command, parameters)
283            .await?
284            .ok_or_else(|| ArcadeDbError::NotFound {
285                operation: "upsert_returning".into(),
286                detail: command.into(),
287            })
288    }
289
290    /// Typed lookup by a (single or composite) key on `type_name`: builds
291    /// `SELECT FROM {type} WHERE k1 = :k0 AND k2 = :k1 LIMIT 1` with bound
292    /// parameters — no identity concept imported, just the Java API's
293    /// `lookupByKey` semantics over plain equality.
294    ///
295    /// Property/type names are validated identifiers (ASCII alphanumerics
296    /// and `_`); values are bound, never interpolated.
297    pub async fn lookup_by_key<T>(
298        &self,
299        database: &str,
300        type_name: &str,
301        key: &[(&str, crate::GrpcValue)],
302    ) -> Result<Option<T>>
303    where
304        T: for<'r> TryFrom<&'r GrpcRecord, Error = RecordDecodeError>,
305    {
306        if key.is_empty() {
307            return Err(ArcadeDbError::InvalidInput {
308                message: "lookup_by_key: key must name at least one property".into(),
309            });
310        }
311        let t = validate_identifier(type_name, "type name")?;
312        let mut sql = format!("SELECT FROM {t}");
313        let mut params = std::collections::HashMap::new();
314        for (i, (column, value)) in key.iter().enumerate() {
315            let column = validate_identifier(column, "property name")?;
316            sql.push_str(if i == 0 { " WHERE " } else { " AND " });
317            sql.push_str(&format!("{column} = :key{i}"));
318            params.insert(format!("key{i}"), value.clone());
319        }
320        sql.push_str(" LIMIT 1");
321        self.fetch_optional(database, &sql, params).await
322    }
323
324    /// Count all records of a type (polymorphic — ArcadeDB `SELECT FROM
325    /// type` includes subtypes), the Java API's `countType`. One
326    /// [`query_scalar`](Self::query_scalar) roundtrip.
327    pub async fn count_type(&self, database: &str, type_name: &str) -> Result<i64> {
328        let t = validate_identifier(type_name, "type name")?;
329        self.query_scalar::<i64>(
330            database,
331            &format!("SELECT count(*) AS count FROM {t}"),
332            std::collections::HashMap::new(),
333        )
334        .await?
335        .ok_or_else(|| ArcadeDbError::NotFound {
336            operation: "count_type".into(),
337            detail: format!("no count row returned for `{t}`"),
338        })
339    }
340}
341
342/// A one-column row's value, for [`ArcadeDbClient::query_scalar`] — the
343/// proto row is a map, so "the scalar" is only well-defined for exactly one
344/// property.
345pub(crate) fn single_column_value<'r>(rec: &'r GrpcRecord, query: &str) -> Result<&'r GrpcValue> {
346    if rec.properties.len() != 1 {
347        return Err(ArcadeDbError::InvalidInput {
348            message: format!(
349                "query_scalar: `{query}` returned a {}-column row; exactly one column is required",
350                rec.properties.len()
351            ),
352        });
353    }
354    Ok(rec.properties.values().next().expect("len checked == 1"))
355}