Skip to main content

arcadedb_protocol/
batch.rs

1//! Multi-statement units — the [`ArcadeDbClient::batch`] facade.
2//!
3//! Wraps the `sqlscript` batch language and the create-or-update edge
4//! keyed by its `(out, in)` pair.
5//!
6//! Type names are validated identifiers; rid strings come from parsed
7//! [`Link`](crate::Link)s (format-validated), values are bound parameters.
8
9use crate::client::{validate_identifier, ArcadeDbClient};
10use crate::error::{ArcadeDbError, Result};
11use crate::proto::com::arcadedb::grpc::ExecuteCommandResponse;
12
13/// Multi-statement units. Obtain via [`ArcadeDbClient::batch`].
14#[derive(Clone)]
15pub struct Batch {
16    client: ArcadeDbClient,
17}
18
19impl Batch {
20    pub(crate) fn new(client: ArcadeDbClient) -> Self {
21        Self { client }
22    }
23
24    /// Run a `sqlscript` script — multiple statements in one roundtrip.
25    /// The script executes statement-by-statement server-side; an error
26    /// aborts the remainder.
27    pub async fn script(&self, database: &str, script: &str) -> Result<ExecuteCommandResponse> {
28        self.client
29            .execute_language(database, "sqlscript", script)
30            .await
31    }
32
33    /// Create-or-update an edge identified by its `(out, in)` endpoints —
34    /// the typed shape `UPDATE … UPSERT` cannot express (unavailable
35    /// on edges): find the existing edge, update it, or
36    /// create it with the given properties.
37    ///
38    /// Two roundtrips on the update path (find + update), one on create.
39    /// `props` keys must be valid identifiers; rid strings are
40    /// format-validated [`Link`](crate::Link)s.
41    pub async fn upsert_edge(
42        &self,
43        database: &str,
44        edge_type: &str,
45        from: &crate::Link,
46        to: &crate::Link,
47        props: impl Into<crate::encode::Params>,
48    ) -> Result<()> {
49        let e = validate_identifier(edge_type, "edge type")?;
50        let props = props.into();
51        let from_rid = from.to_rid_string();
52        let to_rid = to.to_rid_string();
53
54        // Endpoint matching uses the `@out`/`@in` record intrinsics — the
55        // same family as `@rid`/`@type`: always available, no bare form.
56        // Bare `out`/`in` are the graph FUNCTIONS (`out('EDGE')`/
57        // `in('EDGE')`), not endpoint properties, and never match as
58        // equality targets.
59        let existing = self
60            .client
61            .query_with_values(
62                database,
63                &format!("SELECT FROM {e} WHERE @out = :__out AND @in = :__in LIMIT 1"),
64                crate::params! {
65                    __out: crate::encode::link_v(from_rid.clone()),
66                    __in: crate::encode::link_v(to_rid.clone()),
67                },
68            )
69            .await?;
70
71        match existing.records.first() {
72            Some(edge) => {
73                let rid = edge.rid.clone();
74                if props.0.is_empty() {
75                    return Ok(());
76                }
77                let mut set = String::new();
78                let mut params = std::collections::HashMap::new();
79                for (i, (k, v)) in props.0.into_iter().enumerate() {
80                    let k = validate_identifier(&k, "property name")?;
81                    if i > 0 {
82                        set.push_str(", ");
83                    }
84                    set.push_str(&format!("{k} = :{k}"));
85                    params.insert(k, v);
86                }
87                self.client
88                    .execute_with_values(database, &format!("UPDATE {rid} SET {set}"), params)
89                    .await?;
90                Ok(())
91            }
92            None => {
93                let mut sql = format!("CREATE EDGE {e} FROM {from_rid} TO {to_rid}");
94                if !props.0.is_empty() {
95                    let mut set = String::new();
96                    let mut params = std::collections::HashMap::new();
97                    for (i, (k, v)) in props.0.into_iter().enumerate() {
98                        let k = validate_identifier(&k, "property name")?;
99                        if i > 0 {
100                            set.push_str(", ");
101                        }
102                        set.push_str(&format!("{k} = :{k}"));
103                        params.insert(k, v);
104                    }
105                    sql.push_str(&format!(" SET {set}"));
106                    self.client
107                        .execute_with_values(database, &sql, params)
108                        .await?;
109                } else {
110                    self.client.execute(database, &sql).await?;
111                }
112                Ok(())
113            }
114        }
115    }
116
117    /// Apply DDL statements one-by-one. With `idempotent = true`,
118    /// `AlreadyExists` is treated as success (re-runnable
119    /// migrations). Returns how many statements were newly applied.
120    pub async fn apply_ddl(
121        &self,
122        database: &str,
123        statements: &[&str],
124        idempotent: bool,
125    ) -> Result<usize> {
126        let mut applied = 0;
127        for statement in statements {
128            match self.client.execute(database, statement).await {
129                Ok(_) => applied += 1,
130                Err(e) => {
131                    if idempotent && matches!(e, ArcadeDbError::AlreadyExists { .. }) {
132                        tracing::debug!(statement = %statement, "DDL already applied");
133                        continue;
134                    }
135                    return Err(e);
136                }
137            }
138        }
139        Ok(applied)
140    }
141}
142
143/// A buffering [`Batch::script`] writer: statements accumulate and flush
144/// as one roundtrip per `FLUSH_AT` statements, tail via [`Self::finish`].
145pub struct ScriptBuffer {
146    client: ArcadeDbClient,
147    database: String,
148    script: String,
149    stmts: usize,
150}
151
152/// Statements per roundtrip.
153const FLUSH_AT: usize = 500;
154
155impl ScriptBuffer {
156    pub(crate) fn new(client: ArcadeDbClient, database: impl Into<String>) -> Self {
157        Self {
158            client,
159            database: database.into(),
160            script: String::new(),
161            stmts: 0,
162        }
163    }
164
165    /// Append one statement; flushes automatically at the batch size.
166    pub async fn push(&mut self, stmt: &str) -> Result<()> {
167        use std::fmt::Write as _;
168        let _ = writeln!(self.script, "{stmt}");
169        self.stmts += 1;
170        if self.stmts >= FLUSH_AT {
171            self.flush().await?;
172        }
173        Ok(())
174    }
175
176    async fn flush(&mut self) -> Result<()> {
177        if self.script.is_empty() {
178            return Ok(());
179        }
180        let script = std::mem::take(&mut self.script);
181        self.stmts = 0;
182        self.client
183            .execute_language(&self.database, "sqlscript", &script)
184            .await?;
185        Ok(())
186    }
187
188    /// Flush the tail. Call once after the last push.
189    pub async fn finish(&mut self) -> Result<()> {
190        self.flush().await
191    }
192}
193
194impl Batch {
195    /// A buffering script writer bound to this client (see [`ScriptBuffer`]).
196    pub fn script_buffer(&self, database: impl Into<String>) -> ScriptBuffer {
197        ScriptBuffer::new(self.client.clone(), database)
198    }
199}