Skip to main content

arcadedb_protocol/client/
records.rs

1//! Record writes — single-record CRUD by rid plus the bulk insert/upsert
2//! RPCs for many-row loads.
3
4use super::*;
5
6#[cfg(feature = "rayon")]
7use super::results::par_min_records;
8
9/// DTO → wire-record conversion for the bulk-upsert path: each row is an
10/// independent encode (string clones dominate), so under the `rayon` feature
11/// large batches convert on the global pool — threshold-gated so small
12/// upserts keep the sequential path.
13///
14/// `Send` is required unconditionally for signature simplicity: DTOs are
15/// plain data in practice; a genuinely `!Send` DTO can still call
16/// `to_grpc_record` + [`ArcadeDbClient::bulk_upsert`] directly.
17fn records_from_dtos<T: crate::record::ToGrpcRecord + Send>(
18    rows: Vec<T>,
19    target_class: &str,
20) -> Vec<GrpcRecord> {
21    #[cfg(feature = "rayon")]
22    if rows.len() >= par_min_records() {
23        use rayon::prelude::*;
24        return rows
25            .into_par_iter()
26            .map(|row| row.to_grpc_record(target_class))
27            .collect();
28    }
29    rows.into_iter()
30        .map(|row| row.to_grpc_record(target_class))
31        .collect()
32}
33
34impl ArcadeDbClient {
35    /// Create a record of `class_name` from `(property, value)` pairs — the
36    /// typed single-record counterpart of INSERT-INTO SQL. Returns the
37    /// server-assigned rid.
38    pub async fn create_record(
39        &self,
40        database: &str,
41        class_name: &str,
42        props: Vec<(&str, crate::GrpcValue)>,
43    ) -> Result<CreateRecordResponse> {
44        let req = CreateRecordRequest {
45            database: database.into(),
46            credentials: Some(self.auth.creds.clone()),
47            r#type: class_name.into(),
48            record: Some(crate::rec(class_name, props)),
49            transaction: None,
50        };
51        Ok(self
52            .data
53            .clone()
54            .create_record(self.add_auth_headers(tonic::Request::new(req)))
55            .await
56            .map_err(|e| map_rpc_error("create record", class_name, e))?
57            .into_inner())
58    }
59
60    /// Partially update a record by rid: only the given properties change,
61    /// everything else is left untouched (`UpdateRecord`'s `partial` payload).
62    /// The typed alternative to escaped-literal SET SQL; pair with
63    /// [`changed_param_map`](crate::record::changed_param_map) for diff-based
64    /// writes from DTOs.
65    ///
66    /// Returns whether a record was actually updated (unknown rid → `false`).
67    pub async fn update_record_partial(
68        &self,
69        database: &str,
70        rid: &crate::Link,
71        props: impl Into<crate::encode::Params>,
72    ) -> Result<bool> {
73        let req = UpdateRecordRequest {
74            database: database.into(),
75            credentials: Some(self.auth.creds.clone()),
76            rid: rid.to_rid_string(),
77            payload: Some(Payload::Partial(PropertiesUpdate {
78                properties: props.into().0,
79            })),
80            transaction: None,
81        };
82        let resp: UpdateRecordResponse = self
83            .data
84            .clone()
85            .update_record(self.add_auth_headers(tonic::Request::new(req)))
86            .await
87            .map_err(|e| map_rpc_error("update record", &rid.to_string(), e))?
88            .into_inner();
89        if !resp.success {
90            // UpdateRecordResponse carries no server message — the rid is the
91            // only context available.
92            return Err(ArcadeDbError::CommandFailed {
93                operation: "update record".into(),
94                message: rid.to_string(),
95                affected: None,
96            });
97        }
98        Ok(resp.updated)
99    }
100
101    /// Delete a record by rid. Returns whether a record was actually removed
102    /// (already-absent rid → `false`).
103    pub async fn delete_record(&self, database: &str, rid: &crate::Link) -> Result<bool> {
104        let req = DeleteRecordRequest {
105            database: database.into(),
106            rid: rid.to_rid_string(),
107            credentials: Some(self.auth.creds.clone()),
108            transaction: None,
109        };
110        let resp = self
111            .data
112            .clone()
113            .delete_record(self.add_auth_headers(tonic::Request::new(req)))
114            .await
115            .map_err(|e| map_rpc_error("delete record", &rid.to_string(), e))?
116            .into_inner();
117        if !resp.success {
118            return Err(ArcadeDbError::CommandFailed {
119                operation: format!("delete record {rid}"),
120                message: resp.message,
121                affected: None,
122            });
123        }
124        Ok(resp.deleted)
125    }
126
127    /// Bulk-insert rows into `target_class` via the gRPC `BulkInsert` RPC — a
128    /// single round trip for many records. `key_columns` + ignore-conflict make
129    /// it idempotent (safe to re-run on a non-empty table). Used by the test
130    /// fixture generators to seed data efficiently.
131    ///
132    /// Returns the server's [`InsertSummary`] (inserted/updated/ignored counts).
133    pub async fn bulk_insert(
134        &self,
135        database: &str,
136        target_class: &str,
137        key_columns: &[&str],
138        rows: Vec<GrpcRecord>,
139    ) -> Result<InsertSummary> {
140        let creds = self.auth.creds.clone();
141        let req = BulkInsertRequest {
142            database: database.into(),
143            credentials: Some(creds.clone()),
144            options: Some(InsertOptions {
145                target_class: target_class.into(),
146                key_columns: key_columns.iter().map(|s| (*s).to_string()).collect(),
147                // Idempotent re-runs.
148                conflict_mode: ConflictMode::ConflictIgnore as i32,
149                // The server's bulkInsert handler reads database + credentials
150                // from options, not the top-level request fields.
151                database: database.into(),
152                credentials: Some(creds),
153                ..Default::default()
154            }),
155            rows,
156            transaction: None,
157        };
158
159        let resp = self
160            .data
161            .clone()
162            .bulk_insert(self.add_auth_headers(tonic::Request::new(req)))
163            .await
164            .map_err(|e| map_rpc_error("bulk insert", target_class, e))?
165            .into_inner();
166
167        tracing::info!(
168            class = %target_class,
169            inserted = resp.inserted,
170            ignored = resp.ignored,
171            failed = resp.failed,
172            time_ms = resp.execution_time_ms,
173            "bulk insert"
174        );
175        Ok(resp)
176    }
177
178    /// Bulk upsert rows into `target_class` via the gRPC `BulkInsert` RPC with
179    /// `CONFLICT_UPDATE` (mode 1): key columns are matched against existing
180    /// records and the non-key columns are overwritten. One round trip for many
181    /// records — the batch analogue of `UPDATE ... UPSERT`, which the SQL path
182    /// only accepts when the WHERE columns carry an index.
183    ///
184    /// `key_columns` must be covered by an index for conflict detection to be
185    /// reliable (a UNIQUE index on the match key is the sanctioned shape).
186    /// `update_columns_on_conflict` limits which columns are overwritten on a
187    /// match; empty = merge all non-key columns present on the incoming record.
188    ///
189    /// Returns the server's [`InsertSummary`] (inserted/updated/ignored counts).
190    pub async fn bulk_upsert(
191        &self,
192        database: &str,
193        target_class: &str,
194        key_columns: &[&str],
195        update_columns_on_conflict: &[&str],
196        rows: Vec<GrpcRecord>,
197    ) -> Result<InsertSummary> {
198        let creds = self.auth.creds.clone();
199        let req = BulkInsertRequest {
200            database: database.into(),
201            credentials: Some(creds.clone()),
202            options: Some(InsertOptions {
203                target_class: target_class.into(),
204                key_columns: key_columns.iter().map(|s| (*s).to_string()).collect(),
205                // CONFLICT_UPDATE = 1 (upsert/update on match).
206                conflict_mode: ConflictMode::ConflictUpdate as i32,
207                update_columns_on_conflict: update_columns_on_conflict
208                    .iter()
209                    .map(|s| (*s).to_string())
210                    .collect(),
211                database: database.into(),
212                credentials: Some(creds),
213                ..Default::default()
214            }),
215            rows,
216            transaction: None,
217        };
218
219        let resp = self
220            .data
221            .clone()
222            .bulk_insert(self.add_auth_headers(tonic::Request::new(req)))
223            .await
224            .map_err(|e| map_rpc_error("bulk upsert", target_class, e))?
225            .into_inner();
226
227        tracing::info!(
228            class = %target_class,
229            inserted = resp.inserted,
230            updated = resp.updated,
231            ignored = resp.ignored,
232            failed = resp.failed,
233            time_ms = resp.execution_time_ms,
234            "bulk upsert"
235        );
236        Ok(resp)
237    }
238
239    /// The typed [`bulk_upsert`](Self::bulk_upsert): rows are
240    /// `RecordEncode` DTOs, the conflict key comes from the DTO's
241    /// `#[record(key)]` fields (`ToGrpcRecord::KEY_COLUMNS`) — the call
242    /// site cannot disagree with the DTO about the identity — and every
243    /// present column is merged on conflict (absent `Option`s keep their
244    /// stored values).
245    ///
246    /// Errors up front when the DTO declares no key columns.
247    pub async fn bulk_upsert_dtos<T>(
248        &self,
249        database: &str,
250        target_class: &str,
251        rows: Vec<T>,
252    ) -> Result<InsertSummary>
253    where
254        T: crate::record::ToGrpcRecord + Send,
255    {
256        let keys = T::KEY_COLUMNS;
257        if keys.is_empty() {
258            return Err(ArcadeDbError::InvalidInput {
259                message: format!(
260                    "bulk_upsert_dtos: `{}` declares no #[record(key)] columns — \
261                     the server cannot detect conflicts without a key",
262                    std::any::type_name::<T>(),
263                ),
264            });
265        }
266        let records = records_from_dtos(rows, target_class);
267        self.bulk_upsert(database, target_class, keys, &[], records)
268            .await
269    }
270}