Skip to main content

arcadedb_protocol/client/
database.rs

1//! Bound handle — [`DatabaseClient`], a client pinned to one database so
2//! call sites drop the `database: &str` parameter.
3
4use super::*;
5
6// ---------------------------------------------------------------------------
7// Bound handle — a client pinned to one database
8// ---------------------------------------------------------------------------
9
10/// An [`ArcadeDbClient`] bound to one database: every delegated method drops
11/// the `database: &str` parameter. The connect-time name is the single source
12/// of truth, which removes the per-call-site repetition *and* the wrong-db
13/// mistake class.
14///
15/// ```ignore
16/// let db = ArcadeDbClient::connect(addr, user, pass, "mydb").await?;
17/// let res = db.query("SELECT FROM item LIMIT 10").await?;
18/// ```
19///
20/// Un-delegated methods stay reachable through `Deref<Target =
21/// ArcadeDbClient>` (with the explicit parameter).
22#[derive(Clone)]
23pub struct DatabaseClient {
24    client: ArcadeDbClient,
25    database: String,
26}
27
28impl std::ops::Deref for DatabaseClient {
29    type Target = ArcadeDbClient;
30    fn deref(&self) -> &Self::Target {
31        &self.client
32    }
33}
34
35impl std::ops::DerefMut for DatabaseClient {
36    fn deref_mut(&mut self) -> &mut Self::Target {
37        &mut self.client
38    }
39}
40
41impl ArcadeDbClient {
42    /// Bind this client to `database`, producing a [`DatabaseClient`] whose
43    /// methods omit the database parameter. Cheap: clones the channel handle.
44    pub fn to_database(&self, database: impl Into<String>) -> DatabaseClient {
45        DatabaseClient {
46            client: self.clone(),
47            database: database.into(),
48        }
49    }
50}
51
52impl DatabaseClient {
53    /// The multi-statement facade, database-bound (see [`crate::batch::Batch`]).
54    pub fn batch(&self) -> crate::batch::Batch {
55        self.client.batch()
56    }
57
58    /// [`ArcadeDbClient::connect`] straight into a bound handle.
59    pub async fn connect(
60        addr: &str,
61        username: &str,
62        password: &str,
63        database: &str,
64    ) -> Result<Self> {
65        Ok(ArcadeDbClient::connect(addr, username, password, database)
66            .await?
67            .to_database(database))
68    }
69
70    /// The bound database name.
71    pub fn database(&self) -> &str {
72        &self.database
73    }
74
75    /// SQL read.
76    pub async fn query(&self, query: &str) -> Result<QueryResult> {
77        self.client.query(&self.database, query).await
78    }
79
80    /// Parameterized SQL read (`params! { .. }` or a DTO's `to_param_map()`).
81    pub async fn query_with_values(
82        &self,
83        query: &str,
84        parameters: impl Into<crate::encode::Params>,
85    ) -> Result<QueryResult> {
86        self.client
87            .query_with_values(&self.database, query, parameters)
88            .await
89    }
90
91    /// SQL DDL/DML command.
92    pub async fn execute(&self, command: &str) -> Result<ExecuteCommandResponse> {
93        self.client.execute(&self.database, command).await
94    }
95
96    /// Parameterized SQL command.
97    pub async fn execute_with_values(
98        &self,
99        command: &str,
100        parameters: impl Into<crate::encode::Params>,
101    ) -> Result<ExecuteCommandResponse> {
102        self.client
103            .execute_with_values(&self.database, command, parameters)
104            .await
105    }
106
107    /// Server-streaming SQL read.
108    pub async fn stream_query<F>(&self, query: &str, on_batch: F) -> Result<StreamSummary>
109    where
110        F: FnMut(&QueryResultBatch) -> ControlFlow<()>,
111    {
112        self.client
113            .stream_query(&self.database, query, on_batch)
114            .await
115    }
116
117    /// Parameterized server-streaming SQL read.
118    pub async fn stream_query_with_values<F>(
119        &self,
120        query: &str,
121        parameters: impl Into<crate::encode::Params>,
122        on_batch: F,
123    ) -> Result<StreamSummary>
124    where
125        F: FnMut(&QueryResultBatch) -> ControlFlow<()>,
126    {
127        self.client
128            .stream_query_with_values(&self.database, query, parameters, on_batch)
129            .await
130    }
131
132    /// Direct record fetch by rid.
133    pub async fn lookup_by_rid(&self, rid: &crate::Link) -> Result<Option<GrpcRecord>> {
134        self.client.lookup_by_rid(&self.database, rid).await
135    }
136
137    /// Typed single-record fetch.
138    pub async fn lookup<T>(&self, rid: &crate::Link) -> Result<Option<T>>
139    where
140        T: for<'a> TryFrom<&'a GrpcRecord, Error = crate::record::RecordDecodeError>,
141    {
142        self.client.lookup(&self.database, rid).await
143    }
144
145    /// Create a record from `(property, value)` pairs; returns the new rid.
146    pub async fn create_record(
147        &self,
148        class_name: &str,
149        props: Vec<(&str, crate::GrpcValue)>,
150    ) -> Result<CreateRecordResponse> {
151        self.client
152            .create_record(&self.database, class_name, props)
153            .await
154    }
155
156    /// Partially update a record by rid.
157    pub async fn update_record_partial(
158        &self,
159        rid: &crate::Link,
160        props: impl Into<crate::encode::Params>,
161    ) -> Result<bool> {
162        self.client
163            .update_record_partial(&self.database, rid, props)
164            .await
165    }
166
167    /// [`stream_query_with_values`](Self::stream_query_with_values) with
168    /// explicit execution knobs (bound database).
169    pub async fn stream_query_with_options<F>(
170        &self,
171        query: &str,
172        parameters: impl Into<crate::encode::Params>,
173        options: crate::stream::StreamOptions,
174        on_batch: F,
175    ) -> Result<StreamSummary>
176    where
177        F: FnMut(&QueryResultBatch) -> ControlFlow<()>,
178    {
179        self.client
180            .stream_query_with_options(&self.database, query, parameters, options, on_batch)
181            .await
182    }
183
184    /// Typed row streaming (bound database) — decoded rows passed to
185    /// `on_row` as they arrive, no result-set buffering.
186    pub async fn stream_query_rows<T, F>(
187        &self,
188        query: &str,
189        parameters: impl Into<crate::encode::Params>,
190        on_row: F,
191    ) -> Result<StreamSummary>
192    where
193        T: for<'r> TryFrom<&'r GrpcRecord, Error = crate::record::RecordDecodeError>,
194        F: FnMut(T) -> ControlFlow<()>,
195    {
196        self.client
197            .stream_query_rows(&self.database, query, parameters, on_row)
198            .await
199    }
200
201    /// Delete a record by rid.
202    pub async fn delete_record(&self, rid: &crate::Link) -> Result<bool> {
203        self.client.delete_record(&self.database, rid).await
204    }
205
206    /// Typed fetch of at most one row (bound database).
207    pub async fn fetch_optional<T>(
208        &self,
209        query: &str,
210        parameters: impl Into<crate::encode::Params>,
211    ) -> Result<Option<T>>
212    where
213        T: for<'r> TryFrom<&'r GrpcRecord, Error = crate::record::RecordDecodeError>,
214    {
215        self.client
216            .fetch_optional(&self.database, query, parameters)
217            .await
218    }
219
220    /// Typed one-row fetch (bound database); empty result is
221    /// [`ArcadeDbError::NotFound`].
222    pub async fn fetch_one<T>(
223        &self,
224        query: &str,
225        parameters: impl Into<crate::encode::Params>,
226    ) -> Result<T>
227    where
228        T: for<'r> TryFrom<&'r GrpcRecord, Error = crate::record::RecordDecodeError>,
229    {
230        self.client
231            .fetch_one(&self.database, query, parameters)
232            .await
233    }
234
235    /// Single-column scalar decode (bound database).
236    pub async fn query_scalar<T>(
237        &self,
238        query: &str,
239        parameters: impl Into<crate::encode::Params>,
240    ) -> Result<Option<T>>
241    where
242        T: for<'de> crate::record::FromGrpcValue<'de>,
243    {
244        self.client
245            .query_scalar(&self.database, query, parameters)
246            .await
247    }
248
249    /// Write command returning the stored row, decoded (bound database);
250    /// `Ok(None)` when the statement matched nothing.
251    pub async fn write_returning_optional<T>(
252        &self,
253        command: &str,
254        parameters: impl Into<crate::encode::Params>,
255    ) -> Result<Option<T>>
256    where
257        T: for<'r> TryFrom<&'r GrpcRecord, Error = crate::record::RecordDecodeError>,
258    {
259        self.client
260            .write_returning_optional(&self.database, command, parameters)
261            .await
262    }
263
264    /// Write command returning the stored row, decoded (bound database).
265    pub async fn upsert_returning<T>(
266        &self,
267        command: &str,
268        parameters: impl Into<crate::encode::Params>,
269    ) -> Result<T>
270    where
271        T: for<'r> TryFrom<&'r GrpcRecord, Error = crate::record::RecordDecodeError>,
272    {
273        self.client
274            .upsert_returning(&self.database, command, parameters)
275            .await
276    }
277
278    /// Typed lookup by (composite) key (bound database).
279    pub async fn lookup_by_key<T>(
280        &self,
281        type_name: &str,
282        key: &[(&str, crate::GrpcValue)],
283    ) -> Result<Option<T>>
284    where
285        T: for<'r> TryFrom<&'r GrpcRecord, Error = crate::record::RecordDecodeError>,
286    {
287        self.client
288            .lookup_by_key(&self.database, type_name, key)
289            .await
290    }
291
292    /// Count all records of a type (bound database).
293    pub async fn count_type(&self, type_name: &str) -> Result<i64> {
294        self.client.count_type(&self.database, type_name).await
295    }
296
297    /// Retrying transaction closure on the bound database.
298    pub async fn run_transaction<T, F, Fut>(
299        &self,
300        isolation: TransactionIsolation,
301        retries: u32,
302        body: F,
303    ) -> Result<T>
304    where
305        F: Fn(TxCommands) -> Fut,
306        Fut: std::future::Future<Output = Result<T>>,
307    {
308        self.client
309            .run_transaction(&self.database, isolation, retries, body)
310            .await
311    }
312
313    /// Idempotent bulk insert (ignore-on-conflict).
314    pub async fn bulk_insert(
315        &self,
316        target_class: &str,
317        key_columns: &[&str],
318        rows: Vec<GrpcRecord>,
319    ) -> Result<InsertSummary> {
320        self.client
321            .bulk_insert(&self.database, target_class, key_columns, rows)
322            .await
323    }
324
325    /// Bulk upsert (update-on-conflict).
326    pub async fn bulk_upsert(
327        &self,
328        target_class: &str,
329        key_columns: &[&str],
330        update_columns_on_conflict: &[&str],
331        rows: Vec<GrpcRecord>,
332    ) -> Result<InsertSummary> {
333        self.client
334            .bulk_upsert(
335                &self.database,
336                target_class,
337                key_columns,
338                update_columns_on_conflict,
339                rows,
340            )
341            .await
342    }
343
344    /// Typed bulk upsert from `ToGrpcRecord` DTOs.
345    pub async fn bulk_upsert_dtos<T>(
346        &self,
347        target_class: &str,
348        rows: Vec<T>,
349    ) -> Result<InsertSummary>
350    where
351        T: crate::record::ToGrpcRecord + Send,
352    {
353        self.client
354            .bulk_upsert_dtos(&self.database, target_class, rows)
355            .await
356    }
357
358    /// Begin a drop-safe transaction on the bound database.
359    pub async fn transaction(&self, isolation: TransactionIsolation) -> Result<Transaction<'_>> {
360        self.client.transaction(&self.database, isolation).await
361    }
362
363    /// Command in an explicit language (`"sql"`, `"cypher"`, …).
364    pub async fn execute_language(
365        &self,
366        language: &str,
367        command: &str,
368    ) -> Result<ExecuteCommandResponse> {
369        self.client
370            .execute_language(&self.database, language, command)
371            .await
372    }
373
374    /// Cypher read query.
375    pub async fn cypher_query(&self, query: &str) -> Result<QueryResult> {
376        self.client.cypher_query(&self.database, query).await
377    }
378
379    /// Cypher write command.
380    pub async fn cypher_execute(&self, command: &str) -> Result<ExecuteCommandResponse> {
381        self.client.cypher_execute(&self.database, command).await
382    }
383}