arcadedb_protocol/client/
query.rs1use super::*;
5
6impl ArcadeDbClient {
7 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 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 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 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 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 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 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 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 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 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 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
342pub(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}