Skip to main content

arcadedb_protocol/
encode.rs

1//! Ergonomic constructors for `GrpcRecord` / `GrpcValue` — the encoder side of
2//! the [`crate::decode`] bridge. Lets fixture/test code build rows as plain Rust
3//! values and bulk-insert them via gRPC, instead of hand-writing SQL or protobuf
4//! boilerplate.
5
6#[cfg(feature = "decimal")]
7use crate::proto::com::arcadedb::grpc::GrpcDecimal;
8use crate::proto::com::arcadedb::grpc::{
9    grpc_value::Kind, GrpcEmbedded, GrpcLink, GrpcList, GrpcMap, GrpcRecord, GrpcValue,
10};
11
12/// Shorthand for an empty `logical_type` (the common case).
13fn gv(kind: Kind) -> GrpcValue {
14    GrpcValue {
15        kind: Some(kind),
16        logical_type: String::new(),
17    }
18}
19
20pub fn str_v(s: impl Into<String>) -> GrpcValue {
21    gv(Kind::StringValue(s.into()))
22}
23pub fn i64_v(n: i64) -> GrpcValue {
24    gv(Kind::Int64Value(n))
25}
26pub fn i32_v(n: i32) -> GrpcValue {
27    gv(Kind::Int32Value(n))
28}
29pub fn f32_v(n: f32) -> GrpcValue {
30    gv(Kind::FloatValue(n))
31}
32pub fn bool_v(b: bool) -> GrpcValue {
33    gv(Kind::BoolValue(b))
34}
35pub fn f64_v(d: f64) -> GrpcValue {
36    gv(Kind::DoubleValue(d))
37}
38/// A byte blob (the generated proto spells `bytes` as `Vec<u8>`).
39pub fn bytes_v(b: impl Into<Vec<u8>>) -> GrpcValue {
40    gv(Kind::BytesValue(b.into()))
41}
42/// An embedded record value.
43pub fn embedded_v(type_name: &str, fields: Vec<(&str, GrpcValue)>) -> GrpcValue {
44    gv(Kind::EmbeddedValue(GrpcEmbedded {
45        r#type: type_name.into(),
46        fields: fields
47            .into_iter()
48            .map(|(k, v)| (k.to_string(), v))
49            .collect(),
50    }))
51}
52
53/// A link to a record by RID (`#bucket:pos`). Used for LINK fields whose
54/// target RID was resolved after the target was inserted.
55pub fn link_v(rid: impl Into<String>) -> GrpcValue {
56    gv(Kind::LinkValue(GrpcLink {
57        rid: rid.into(),
58        r#type: String::new(),
59    }))
60}
61
62/// Build a record of `type_name` from `(field, value)` pairs — values go
63/// through [`IntoGrpcValue`], same coverage as `params!` (no constructor
64/// ceremony at call sites; already-converted `GrpcValue`s pass through).
65/// `rid` is left empty (the server assigns it on insert).
66pub fn rec<T: IntoGrpcValue>(type_name: &str, props: Vec<(&str, T)>) -> GrpcRecord {
67    GrpcRecord {
68        rid: String::new(),
69        r#type: type_name.to_string(),
70        properties: props
71            .into_iter()
72            .map(|(k, v)| (k.to_string(), v.into_value()))
73            .collect(),
74    }
75}
76
77/// A list value from any iterator of already-built values — for
78/// heterogeneous/raw list assembly. Typed slices go through
79/// [`IntoGrpcValue`] on `Vec<T>` (an always-empty list is
80/// `Vec::<GrpcValue>::new().into_value()` via the pass-through impl).
81pub fn list_v(values: impl IntoIterator<Item = GrpcValue>) -> GrpcValue {
82    gv(Kind::ListValue(GrpcList {
83        values: values.into_iter().collect(),
84    }))
85}
86
87/// A map value from `(key, value)` pairs.
88pub fn map_v(entries: impl IntoIterator<Item = (String, GrpcValue)>) -> GrpcValue {
89    gv(Kind::MapValue(GrpcMap {
90        entries: entries.into_iter().collect(),
91    }))
92}
93
94/// A timestamp value (`DATETIME` columns). The wire kind is a UTC timestamp;
95/// this is also the shape `DATE` columns arrive in (midnight-UTC).
96pub fn timestamp_v(t: chrono::DateTime<chrono::Utc>) -> GrpcValue {
97    use chrono::Timelike;
98    gv(Kind::TimestampValue(prost_types::Timestamp {
99        seconds: t.timestamp(),
100        nanos: t.nanosecond() as i32,
101    }))
102}
103
104/// A date value (`DATE` columns) — sent as midnight-UTC on the wire,
105/// matching how the server returns them.
106pub fn date_v(d: chrono::NaiveDate) -> GrpcValue {
107    timestamp_v(d.and_hms_opt(0, 0, 0).expect("midnight is valid").and_utc())
108}
109
110/// An exact-decimal value (`DECIMAL` columns; `decimal` feature). The
111/// unscaled mantissa rides `unscaled` when it fits a signed 64-bit integer,
112/// otherwise big-endian two's-complement in `unscaled_bytes`.
113#[cfg(feature = "decimal")]
114pub fn decimal_v(d: rust_decimal::Decimal) -> GrpcValue {
115    let mantissa = d.mantissa();
116    let (unscaled, unscaled_bytes) = match i64::try_from(mantissa) {
117        Ok(n) => (n, Vec::new()),
118        Err(_) => (0, mantissa.to_be_bytes().to_vec()),
119    };
120    gv(Kind::DecimalValue(GrpcDecimal {
121        unscaled,
122        scale: d.scale() as i32,
123        unscaled_bytes,
124    }))
125}
126
127/// Bound-parameter map for the client's `*_with_values` / `execute_with_values`
128/// methods. Construct it from an array literal (the common case) or wrap an
129/// existing map / a RecordEncode DTO's
130/// [`ToGrpcRecord::to_param_map`](crate::record::ToGrpcRecord) output.
131///
132/// ```ignore
133/// client.query_with_values(db, &sql, [("item_id", i64_v(id))])?;
134/// client.query_with_values(db, &sql, SearchParams { .. }.to_param_map::<Params>())?;
135/// ```
136#[derive(Debug, Clone, Default)]
137pub struct Params(pub std::collections::HashMap<String, GrpcValue>);
138
139impl<T: IntoGrpcValue, const N: usize> From<[(&str, T); N]> for Params {
140    fn from(pairs: [(&str, T); N]) -> Self {
141        Params(
142            pairs
143                .into_iter()
144                .map(|(k, v)| (k.to_string(), v.into_value()))
145                .collect(),
146        )
147    }
148}
149
150impl From<std::collections::HashMap<String, GrpcValue>> for Params {
151    fn from(map: std::collections::HashMap<String, GrpcValue>) -> Self {
152        Params(map)
153    }
154}
155
156/// An aHash map of bound parameters — the `ahash` feature's counterpart of
157/// the std-map conversion above. The parameter map itself stays the crate's
158/// own; only the SOURCE map type is the caller's choice.
159#[cfg(feature = "ahash")]
160impl From<ahash::AHashMap<String, GrpcValue>> for Params {
161    fn from(map: ahash::AHashMap<String, GrpcValue>) -> Self {
162        Params(map.into_iter().collect())
163    }
164}
165
166/// An FxHash map of bound parameters — the `fxhash` feature's counterpart of
167/// the std-map conversion above.
168#[cfg(feature = "fxhash")]
169impl From<rustc_hash::FxHashMap<String, GrpcValue>> for Params {
170    fn from(map: rustc_hash::FxHashMap<String, GrpcValue>) -> Self {
171        Params(map.into_iter().collect())
172    }
173}
174
175/// The no-parameters form — `query_scalar::<i64>(sql, ())` reads naturally
176/// next to param'd calls without reaching for an empty map.
177impl From<()> for Params {
178    fn from((): ()) -> Self {
179        Params(std::collections::HashMap::new())
180    }
181}
182
183impl core::ops::Deref for Params {
184    type Target = std::collections::HashMap<String, GrpcValue>;
185    fn deref(&self) -> &Self::Target {
186        &self.0
187    }
188}
189
190impl Params {
191    /// Build the parameter map from ANY `(name, value)` map — std, aHash,
192    /// FxHash, BTreeMap, a `Vec`, … — without a per-type `From` impl.
193    ///
194    /// ```ignore
195    /// let mut p = ahash::AHashMap::new();
196    /// p.insert("id".to_string(), i64_v(7));
197    /// let params = Params::from_map(p);
198    /// ```
199    pub fn from_map<M: IntoIterator<Item = (String, GrpcValue)>>(map: M) -> Self {
200        Params(map.into_iter().collect())
201    }
202}
203
204/// Collect a parameter map from any iterator of `(name, value)` pairs —
205/// the generic counterpart of the per-hasher `From` impls. `Params` is
206/// also a valid target for the generic map conversions
207/// ([`to_param_map`](crate::record::ToGrpcRecord::to_param_map)).
208impl FromIterator<(String, GrpcValue)> for Params {
209    fn from_iter<T: IntoIterator<Item = (String, GrpcValue)>>(iter: T) -> Self {
210        Params(iter.into_iter().collect())
211    }
212}
213
214// ---------------------------------------------------------------------------
215// Type-directed value conversion (`params!`'s discovery mechanism)
216// ---------------------------------------------------------------------------
217
218/// The encode-side mirror of [`crate::record::FromGrpcValue`]: Rust values
219/// convert to their natural wire kind, so [`params!`](crate::params!) can
220/// accept computed expressions and let trait resolution pick the constructor.
221///
222/// Canonical widths only — bare integer literals bind as `Int64`, float
223/// literals as `Double`. Narrower kinds are opt-in through the explicit
224/// constructors (`i32_v(..)` etc.), mirroring how `RecordEncode` never
225/// silently changes widths.
226pub trait IntoGrpcValue {
227    fn into_value(self) -> GrpcValue;
228}
229
230// Width resolution for integers: `i32` → wire Int32, `i64` → wire Int64 —
231// the TYPE disambiguates. Bare integer literals fall back to Rust's
232// default (`i32` → Int32): suffix them (`1001i64`) or bind a typed
233// value when the column's wire kind matters.
234
235impl IntoGrpcValue for GrpcValue {
236    fn into_value(self) -> GrpcValue {
237        self
238    }
239}
240
241impl IntoGrpcValue for bool {
242    fn into_value(self) -> GrpcValue {
243        bool_v(self)
244    }
245}
246
247impl IntoGrpcValue for i64 {
248    fn into_value(self) -> GrpcValue {
249        i64_v(self)
250    }
251}
252
253impl IntoGrpcValue for f64 {
254    fn into_value(self) -> GrpcValue {
255        f64_v(self)
256    }
257}
258
259impl IntoGrpcValue for &str {
260    fn into_value(self) -> GrpcValue {
261        str_v(self)
262    }
263}
264
265impl IntoGrpcValue for &String {
266    fn into_value(self) -> GrpcValue {
267        str_v(self.as_str())
268    }
269}
270
271impl IntoGrpcValue for String {
272    fn into_value(self) -> GrpcValue {
273        str_v(self)
274    }
275}
276
277impl IntoGrpcValue for std::borrow::Cow<'_, str> {
278    fn into_value(self) -> GrpcValue {
279        str_v(self.into_owned())
280    }
281}
282
283impl IntoGrpcValue for chrono::DateTime<chrono::Utc> {
284    fn into_value(self) -> GrpcValue {
285        timestamp_v(self)
286    }
287}
288
289impl IntoGrpcValue for chrono::NaiveDate {
290    fn into_value(self) -> GrpcValue {
291        date_v(self)
292    }
293}
294
295impl<T: IntoGrpcValue> IntoGrpcValue for Vec<T> {
296    fn into_value(self) -> GrpcValue {
297        list_v(self.into_iter().map(IntoGrpcValue::into_value))
298    }
299}
300
301/// `i32` binds as the wire `Int32` — the type itself is the disambiguator,
302/// matching [`i64`](impl-IntoGrpcValue-for-i64) → `Int64`. No widening, no
303/// runtime decision: callers hand over the width they mean.
304impl IntoGrpcValue for i32 {
305    fn into_value(self) -> GrpcValue {
306        i32_v(self)
307    }
308}
309
310/// String-keyed maps bind as the wire `Map` — the whole map value goes
311/// through one `set`/`params!` entry instead of the caller rebuilding it
312/// with [`map_v`] item by item.
313impl<V: IntoGrpcValue> IntoGrpcValue for std::collections::HashMap<String, V> {
314    fn into_value(self) -> GrpcValue {
315        map_v(self.into_iter().map(|(k, v)| (k, v.into_value())))
316    }
317}
318
319/// aHash maps bind as the wire `Map` too — the same wire kind as
320/// [`std::collections::HashMap`], so an `ahash::AHashMap` can be handed
321/// straight to [`params!`](crate::params!), [`SetClause::set`], a
322/// [`FilterClause`](crate::FilterClause) operator, or [`rec`] without a
323/// std↔aHash conversion in between.
324///
325/// Requires the `ahash` feature.
326#[cfg(feature = "ahash")]
327impl<V: IntoGrpcValue> IntoGrpcValue for ahash::AHashMap<String, V> {
328    fn into_value(self) -> GrpcValue {
329        map_v(self.into_iter().map(|(k, v)| (k, v.into_value())))
330    }
331}
332
333/// FxHash maps (`rustc_hash::FxHashMap`) bind as the wire `Map` — the same
334/// wire kind as [`std::collections::HashMap`].
335///
336/// Requires the `fxhash` feature.
337#[cfg(feature = "fxhash")]
338impl<V: IntoGrpcValue> IntoGrpcValue for rustc_hash::FxHashMap<String, V> {
339    fn into_value(self) -> GrpcValue {
340        map_v(self.into_iter().map(|(k, v)| (k, v.into_value())))
341    }
342}
343
344impl<V: IntoGrpcValue> IntoGrpcValue for std::collections::BTreeMap<String, V> {
345    fn into_value(self) -> GrpcValue {
346        map_v(self.into_iter().map(|(k, v)| (k, v.into_value())))
347    }
348}
349
350/// `char` binds as a single-character string — the symmetric encode of the
351/// decode-side `char` impl.
352impl IntoGrpcValue for char {
353    fn into_value(self) -> GrpcValue {
354        str_v(self.to_string())
355    }
356}
357
358/// Small signed widths bind as the wire `Int32` (lossless: i8/i16 fit).
359/// `u8` is deliberately absent — it would collide with `Vec<u8>` = bytes
360/// under the blanket `Vec<T>` impl; byte-ish u8s belong in `Vec<u8>`.
361impl IntoGrpcValue for i8 {
362    fn into_value(self) -> GrpcValue {
363        i32_v(i32::from(self))
364    }
365}
366
367impl IntoGrpcValue for i16 {
368    fn into_value(self) -> GrpcValue {
369        i32_v(i32::from(self))
370    }
371}
372
373impl IntoGrpcValue for u16 {
374    fn into_value(self) -> GrpcValue {
375        i32_v(i32::from(self))
376    }
377}
378
379/// `u32` binds as the wire `Int64` (u32 does not fit i32).
380impl IntoGrpcValue for u32 {
381    fn into_value(self) -> GrpcValue {
382        i64_v(i64::from(self))
383    }
384}
385
386/// `u64` binds as `Int64` by cast — values above `i64::MAX` wrap; ArcadeDB
387/// has no u64 wire kind, so this mirrors the derive's widening.
388impl IntoGrpcValue for u64 {
389    fn into_value(self) -> GrpcValue {
390        i64_v(self as i64)
391    }
392}
393
394/// `f32` binds as the wire `Float`.
395impl IntoGrpcValue for f32 {
396    fn into_value(self) -> GrpcValue {
397        f32_v(self)
398    }
399}
400
401/// Owned bytes bind as the wire `Bytes` — the symmetric encode of the
402/// decode-side `&[u8]` view. (Specialized: `u8` has no scalar impl, so this
403/// does not overlap the blanket `Vec<T>`.)
404impl IntoGrpcValue for Vec<u8> {
405    fn into_value(self) -> GrpcValue {
406        bytes_v(self)
407    }
408}
409
410/// JSON binds through the bridge — the symmetric encode of the decode-side
411/// `serde_json::Value` impl.
412impl IntoGrpcValue for serde_json::Value {
413    fn into_value(self) -> GrpcValue {
414        crate::decode::json_to_grpc_value(&self)
415    }
416}
417
418// `Option<T>` is deliberately NOT implemented: the wire `oneof kind` HAS
419// NO NULL VARIANT (see the proto — 13 shapes, null is not one of them), so
420// there is no null payload an Option could send; an unset kind binds
421// nothing and the server skips such params entirely. An Option impl would
422// therefore silently drop writes. Absent-or-set semantics live in
423// `SetClause::set_opt` (omit) / `set_or_null` (SQL literal) where the
424// choice is explicit.
425
426#[cfg(feature = "decimal")]
427impl IntoGrpcValue for rust_decimal::Decimal {
428    fn into_value(self) -> GrpcValue {
429        decimal_v(self)
430    }
431}
432
433impl IntoGrpcValue for crate::Link {
434    fn into_value(self) -> GrpcValue {
435        link_v(self.to_rid_string())
436    }
437}
438
439/// Assemble bound parameters with map semantics — the literal form for the
440/// client's `*_with_values` methods.
441///
442/// Keys are identifiers (they become the SQL `:name`s); values go through
443/// [`IntoGrpcValue`] so computed expressions resolve to their natural wire
444/// kind at compile time:
445///
446/// ```ignore
447/// use arcadedb_protocol::{params, date_v};
448///
449/// let min = 0.8f64;
450/// client.query_with_values(db, &sql, params! {
451///     item_id: 1001i64,                        // literal: suffix picks the width
452///     title: "Red Widget",                     // &str → String
453///     filter: {                                // nested map → MapValue
454///         "genre": "utility",
455///         "min_score": min,                    // typed f64 → Double
456///     },
457///     since: date_v(chrono::NaiveDate::from_ymd_opt(2024, 1, 15).unwrap()),
458/// })
459/// ```
460///
461/// Already-converted [`GrpcValue`]s pass through untouched, so explicit
462/// constructors compose (`code: i32_v(n)`); `Vec<T>` binds as a list.
463/// Field punning works too — `item_id,` ≡ `item_id: item_id`.
464#[macro_export]
465macro_rules! params {
466    ($($tokens:tt)+) => {
467        $crate::__params_acc!([] $($tokens)+)
468    };
469}
470
471/// Accumulator backend for [`params!]` — do not use directly.
472#[doc(hidden)]
473#[macro_export]
474macro_rules! __params_acc {
475    // Done: build the map from the accumulated `(String, GrpcValue)` pairs.
476    ([$($acc:tt)*]) => {
477        $crate::Params(::core::iter::FromIterator::from_iter([$($acc)*]))
478    };
479    // Nested map value, more entries follow.
480    ([$($acc:tt)*] $key:ident : { $($mk:tt : $mv:expr),+ $(,)? } , $($rest:tt)+) => {
481        $crate::__params_acc!([
482            $($acc)*
483            (::std::stringify!($key).to_string(), $crate::__private::map_v([
484                $(($mk.to_string(), $crate::IntoGrpcValue::into_value($mv))),+
485            ])),
486        ] $($rest)+)
487    };
488    // Nested map value, last entry.
489    ([$($acc:tt)*] $key:ident : { $($mk:tt : $mv:expr),+ $(,)? } $(,)?) => {
490        $crate::__params_acc!([
491            $($acc)*
492            (::std::stringify!($key).to_string(), $crate::__private::map_v([
493                $(($mk.to_string(), $crate::IntoGrpcValue::into_value($mv))),+
494            ])),
495        ])
496    };
497    // Field punning (`key,` ≡ `key: key`), more entries follow.
498    ([$($acc:tt)*] $key:ident , $($rest:tt)+) => {
499        $crate::__params_acc!([
500            $($acc)*
501            (::std::stringify!($key).to_string(), $crate::IntoGrpcValue::into_value($key)),
502        ] $($rest)+)
503    };
504    // Field punning, last entry.
505    ([$($acc:tt)*] $key:ident $(,)?) => {
506        $crate::__params_acc!([
507            $($acc)*
508            (::std::stringify!($key).to_string(), $crate::IntoGrpcValue::into_value($key)),
509        ])
510    };
511    // Plain value, more entries follow. The expr fragment parses past commas
512    // inside calls/braces; a failed braced-map parse falls through to this arm.
513    ([$($acc:tt)*] $key:ident : $value:expr , $($rest:tt)+) => {
514        $crate::__params_acc!([
515            $($acc)*
516            (::std::stringify!($key).to_string(), $crate::IntoGrpcValue::into_value($value)),
517        ] $($rest)+)
518    };
519    // Plain value, last entry.
520    ([$($acc:tt)*] $key:ident : $value:expr $(,)?) => {
521        $crate::__params_acc!([
522            $($acc)*
523            (::std::stringify!($key).to_string(), $crate::IntoGrpcValue::into_value($value)),
524        ])
525    };
526}
527
528/// Assemble an **embedded record value** — the nestable, value-form sibling
529/// of [`rec`]: same `key: value` entry grammar as [`params!`](crate::params!),
530/// each field dispatching its own [`IntoGrpcValue`], producing the wire's embedded
531/// (`Kind::EmbeddedValue`) shape. Values nest and compose: `vec![embedded!(..),
532/// ..]` is a list of embedded values, and a built value rides anywhere a
533/// value does (`rec` fields, `params!`, `SetClause`) through the
534/// `GrpcValue` pass-through.
535///
536/// ```
537/// # use arcadedb_protocol::{embedded, grpc_value_to_json, rec};
538/// let line = embedded!("note_line", author: "A", position: 1, archived: true);
539/// // Mixed field types in one invocation, no constructors; lists of
540/// // embedded values compose through Vec<GrpcValue>:
541/// let row = rec("note", vec![
542///     ("entries", vec![
543///         line,
544///         embedded!("note_line", author: "B", position: 2, archived: false),
545///     ]),
546/// ]);
547/// assert_eq!(
548///     grpc_value_to_json(&row.properties["entries"]),
549///     serde_json::json!([
550///         {"author": "A", "position": 1, "archived": true},
551///         {"author": "B", "position": 2, "archived": false},
552///     ])
553/// );
554/// ```
555#[macro_export]
556macro_rules! embedded {
557    ($type:expr $(, $($tokens:tt)+)?) => {
558        $crate::__embedded_acc!($type, [] $($($tokens)+)?)
559    };
560}
561
562/// Accumulator backend for [`embedded!`] — do not use directly.
563#[doc(hidden)]
564#[macro_export]
565macro_rules! __embedded_acc {
566    // Done: hand the accumulated (key, value) pairs to the internal
567    // constructor (embedded_v stays codegen-internal; the macro IS the
568    // public surface).
569    ($type:expr, [$($acc:tt)*]) => {
570        $crate::__private::embedded_v(
571            $type,
572            ::core::iter::FromIterator::from_iter([$($acc)*]),
573        )
574    };
575    // Field, more entries follow.
576    ($type:expr, [$($acc:tt)*] $key:ident : $value:expr , $($rest:tt)+) => {
577        $crate::__embedded_acc!(
578            $type, [$($acc)* (::std::stringify!($key), $crate::IntoGrpcValue::into_value($value)),]
579            $($rest)+
580        )
581    };
582    // Field, last entry.
583    ($type:expr, [$($acc:tt)*] $key:ident : $value:expr $(,)?) => {
584        $crate::__embedded_acc!(
585            $type, [$($acc)* (::std::stringify!($key), $crate::IntoGrpcValue::into_value($value)),]
586        )
587    };
588}
589
590// ---------------------------------------------------------------------------
591// Conditional SET-clause assembly
592// ---------------------------------------------------------------------------
593
594/// Accumulates `col = :col` SET fragments and their bound values for
595/// `INSERT INTO … SET …` / `UPDATE … SET …` statements whose shape is only
596/// known at runtime (optional fields, conditional writes).
597///
598/// The placeholder name IS the column name, so a fragment can never reference
599/// a param that wasn't bound — the silently-nulling placeholder/key mismatch
600/// failure mode is unrepresentable by construction.
601///
602/// ```ignore
603/// let clause = SetClause::new()
604///     .set("completed_at", now)
605///     .set_opt("score", score)          // None → column omitted entirely
606///     .set_when(rewrite, "audio_model", model);
607/// let sql = format!("UPDATE t SET {} WHERE id = :id", clause.sql());
608/// client.execute_with_values(&sql, clause.set("id", id).into_params()).await?;
609/// ```
610///
611/// `None` handling is deliberately *omit, don't bind*: on UPDATE paths the
612/// stored value is preserved, on INSERT paths the schema default/null applies.
613///
614/// List writes: [`append`](SetClause::append) is the
615/// server-side append (`col = col || :param`). **Positional element updates
616/// have no server-native form**: `SET list[i] = :v` is
617/// accepted-but-silently-ignored and `PUT list i :v` is a syntax error —
618/// read-modify-write (select the list, patch in Rust,
619/// [`set`](SetClause::set) the whole list) remains the shape for
620/// those.
621#[derive(Debug, Clone, Default)]
622pub struct SetClause {
623    frags: Vec<String>,
624    params: std::collections::HashMap<String, GrpcValue>,
625}
626
627impl SetClause {
628    pub fn new() -> Self {
629        Self::default()
630    }
631
632    /// True when nothing was pushed (callers may want to skip the write).
633    pub fn is_empty(&self) -> bool {
634        self.frags.is_empty()
635    }
636
637    /// Always include `col = :col` with the bound value. Build each column
638    /// once — re-setting emits the fragment twice (last value wins).
639    pub fn set(mut self, col: &str, value: impl IntoGrpcValue) -> Self {
640        self.frags.push(format!("{col} = :{col}"));
641        self.params.insert(col.to_string(), value.into_value());
642        self
643    }
644
645    /// [`set`](Self::set) only when `value` is `Some`.
646    pub fn set_opt<T: IntoGrpcValue>(self, col: &str, value: Option<T>) -> Self {
647        match value {
648            Some(v) => self.set(col, v),
649            None => self,
650        }
651    }
652
653    /// [`set`](Self::set) only when `cond` holds.
654    pub fn set_when(self, cond: bool, col: &str, value: impl IntoGrpcValue) -> Self {
655        if cond {
656            self.set(col, value)
657        } else {
658            self
659        }
660    }
661
662    /// Escape hatch for fragments that are not a plain `col = :col`.
663    /// The fragment must still reference `:name`; `name` is registered
664    /// so it can never dangle.
665    pub fn set_raw(
666        mut self,
667        fragment: impl Into<String>,
668        name: &str,
669        value: impl IntoGrpcValue,
670    ) -> Self {
671        self.frags.push(fragment.into());
672        self.params.insert(name.to_string(), value.into_value());
673        self
674    }
675
676    /// Set a column to a SERVER-SIDE expression (`count = count + 1`,
677    /// `checked_at = sysdate()`) — the increment/anchor forms that have no
678    /// client-side value to bind. Both halves are caller-owned SQL: `col`
679    /// must be a plain schema identifier (same contract as
680    /// [`set`](Self::set), which likewise interpolates it), `expr` is
681    /// inserted verbatim — never data.
682    pub fn set_expr(mut self, col: &str, expr: &str) -> Self {
683        self.frags.push(format!("{col} = {expr}"));
684        self
685    }
686
687    /// Register a param WITHOUT emitting a fragment — for values referenced
688    /// from elsewhere in the statement. Composes with
689    /// [`sql`](Self::sql)/[`into_params`](Self::into_params).
690    pub fn bind(mut self, name: &str, value: impl IntoGrpcValue) -> Self {
691        self.params.insert(name.to_string(), value.into_value());
692        self
693    }
694
695    /// Apply a multi-call step only when `option` is `Some` — the
696    /// conditional-composition form for write shapes that need more than
697    /// one builder call (e.g. [`append`](Self::append) + [`bind`](Self::bind)
698    /// together). `None` passes the clause through untouched. Read-side
699    /// twin: [`FilterClause::apply_if`](crate::FilterClause::apply_if).
700    ///
701    /// ```
702    /// # use arcadedb_protocol::SetClause;
703    /// let clause = SetClause::new()
704    ///     .apply_if(Some("red"), |c, v| c.append("labels", v))
705    ///     .apply_if(None::<String>, |c, v| c.set("note", v));
706    /// assert_eq!(clause.sql(), "labels = labels || :labels__append");
707    /// ```
708    pub fn apply_if<T>(self, option: Option<T>, f: impl FnOnce(Self, T) -> Self) -> Self {
709        match option {
710            Some(v) => f(self, v),
711            None => self,
712        }
713    }
714
715    /// Server-side list append: emits `col = col || :{col}__append` with the
716    /// element bound as a one-element list. One roundtrip, no
717    /// read-merge-write window, works on a NULL column
718    /// (`null || [x] = [x]`) and preserves element kinds.
719    ///
720    /// Chained appends on the same column coalesce into ONE fragment + one
721    /// merged list param. Appending to a column also plain-`set` in the
722    /// same clause is unsupported (build one or the other).
723    ///
724    /// The idempotent append is one statement — `CONTAINS` accepts the same
725    /// single-element list param as a membership test:
726    ///
727    /// ```
728    /// # use arcadedb_protocol::SetClause;
729    /// let clause = SetClause::new().append("labels", "red");
730    /// assert_eq!(clause.sql(), "labels = labels || :labels__append");
731    /// ```
732    ///
733    /// The update's `affected_records` is the "did it change" bool.
734    pub fn append(mut self, col: &str, value: impl IntoGrpcValue) -> Self {
735        let param = format!("{col}__append");
736        match self.params.get_mut(&param) {
737            // Second+ append on the same column: merge into the bound list
738            // and keep the single fragment.
739            Some(GrpcValue {
740                kind: Some(Kind::ListValue(list)),
741                ..
742            }) => list.values.push(value.into_value()),
743            _ => {
744                self.frags.push(format!("{col} = {col} || :{param}"));
745                self.params.insert(param, list_v([value.into_value()]));
746            }
747        }
748        self
749    }
750
751    /// [`set`](Self::set) when `value` is `Some`; **explicitly null the
752    /// column** when `None`.
753    ///
754    /// Unlike [`set_opt`](Self::set_opt) (which omits `None` columns to
755    /// preserve stored values), this is the write-what-you-mean form for
756    /// refresh paths where an absent source field must CLEAR stale data.
757    ///
758    /// The `None` arm cannot bind: the wire oneof has no null kind, so an
759    /// unset value is simply skipped server-side (no property can be
760    /// nulled through a bound parameter) — it falls back to a `col = null`
761    /// SQL literal, the only spelling the engine actually honors.
762    /// The only interpolated text is the column name (caller-owned schema
763    /// identifier, never data).
764    pub fn set_or_null<T: IntoGrpcValue>(mut self, col: &str, value: Option<T>) -> Self {
765        match value {
766            Some(v) => self.set(col, v),
767            None => {
768                self.frags.push(format!("{col} = null"));
769                self
770            }
771        }
772    }
773
774    /// The SET-clause body: `a = :a, b = :b`. Empty string when nothing was
775    /// pushed (callers decide whether an empty SET is valid for their shape).
776    pub fn sql(&self) -> String {
777        self.frags.join(", ")
778    }
779
780    /// Consume into `Params` for `query_with_values` / `execute_with_values`.
781    pub fn into_params(self) -> Params {
782        Params(self.params)
783    }
784}