arcadedb_protocol/
batch.rs1use crate::client::{validate_identifier, ArcadeDbClient};
10use crate::error::{ArcadeDbError, Result};
11use crate::proto::com::arcadedb::grpc::ExecuteCommandResponse;
12
13#[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 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 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 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 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
143pub struct ScriptBuffer {
146 client: ArcadeDbClient,
147 database: String,
148 script: String,
149 stmts: usize,
150}
151
152const 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 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 pub async fn finish(&mut self) -> Result<()> {
190 self.flush().await
191 }
192}
193
194impl Batch {
195 pub fn script_buffer(&self, database: impl Into<String>) -> ScriptBuffer {
197 ScriptBuffer::new(self.client.clone(), database)
198 }
199}