arcadedb_protocol/filter.rs
1//! [`FilterClause`] — WHERE assembly for dynamic queries, the
2//! read-side sibling of [`SetClause`](crate::SetClause).
3//!
4//! Every operator method emits its fragment AND binds its parameter in the
5//! same call — the fragment can never reference a param that wasn't bound.
6//! Values go through [`IntoGrpcValue`]; the only caller-owned text is the
7//! column name (same contract as `SetClause`: treat it like your schema).
8//!
9//! The operator surface follows ArcadeDB's SQL reference
10//! (`sql-where.adoc`):
11//!
12//! - Comparisons `= <> < <= > >=`, `BETWEEN :a AND :b`, `IS [NOT] NULL`.
13//! - `IN :p` — bound lists carry no SQL-text length cap; `NOT IN` is
14//! documented NOT to use the index (complement scan) — see
15//! [`FilterClause::not_in`].
16//! - `CONTAINS :scalar` — collection holds one equal element (**bind
17//! scalars only**: a collection on the right of `CONTAINS` is searched
18//! for as a single *nested* element, not as membership).
19//! - `CONTAINSALL` / `CONTAINSANY :list` — membership over a bound
20//! collection.
21//! - `LIKE` / `ILIKE :pattern` — non-indexed.
22//! - `LIMIT :limit` / `SKIP :skip` accept bound placeholders — call sites
23//! can stop interpolating `{limit}`.
24//!
25//! Two traps worth knowing before naming things:
26//!
27//! - **Param names share the lexer with SQL keywords**: `:after` fails to
28//! *parse* (`AFTER` is reserved by `RETURN BEFORE|AFTER`). Generated
29//! names are identifier-shaped (`{col}`, `{col}__lt`, …) and safe unless
30//! a column is exactly a keyword.
31//! - **`@rid` in WHERE is documented as slow** — prefer the rid as target
32//! (`SELECT FROM #12:3`) or
33//! [`lookup_by_rid`](crate::ArcadeDbClient::lookup_by_rid). The record
34//! intrinsics (`@rid`, `@type`, `@out`, `@in`) ARE valid filter columns.
35
36use std::collections::HashMap;
37
38use crate::encode::{IntoGrpcValue, Params};
39use crate::GrpcValue;
40
41/// Accumulates AND-joined WHERE fragments and their bound values.
42///
43/// ```
44/// # use arcadedb_protocol::FilterClause;
45/// let filter = FilterClause::new()
46/// .filter("is_visible = true")
47/// .gte("release_date", chrono::NaiveDate::from_ymd_opt(2020, 1, 1).unwrap());
48/// assert!(filter.sql().contains("release_date >= :release_date__gte"));
49/// assert_eq!(FilterClause::new().where_sql(), "");
50/// ```
51///
52/// Compose into a query with [`Params`](crate::Params); merge with
53/// [`SetClause`](crate::SetClause) for `UPDATE … SET … WHERE …`.
54#[derive(Debug, Clone, Default)]
55pub struct FilterClause {
56 frags: Vec<String>,
57 params: HashMap<String, GrpcValue>,
58}
59
60impl FilterClause {
61 pub fn new() -> Self {
62 Self::default()
63 }
64
65 /// True when nothing was pushed.
66 pub fn is_empty(&self) -> bool {
67 self.frags.is_empty()
68 }
69
70 /// The WHERE body: `a = :a AND b >= :b__gte`. Empty when nothing
71 /// was pushed.
72 pub fn sql(&self) -> String {
73 self.frags.join(" AND ")
74 }
75
76 /// [`sql`](Self::sql) with the `WHERE` keyword, or `""` when empty
77 /// (no dangling WHERE).
78 pub fn where_sql(&self) -> String {
79 if self.frags.is_empty() {
80 String::new()
81 } else {
82 format!("WHERE {}", self.sql())
83 }
84 }
85
86 /// Consume into `Params` for `query_with_values` / `execute_with_values`.
87 pub fn into_params(self) -> Params {
88 Params(self.params)
89 }
90
91 /// Include a raw fragment as-is. The fragment owns any placeholders it
92 /// references — bind them via [`bind`](Self::bind).
93 pub fn filter(mut self, fragment: impl Into<String>) -> Self {
94 self.frags.push(fragment.into());
95 self
96 }
97
98 /// [`filter`](Self::filter) only when `cond` holds.
99 pub fn filter_when(self, cond: bool, fragment: impl Into<String>) -> Self {
100 if cond {
101 self.filter(fragment)
102 } else {
103 self
104 }
105 }
106
107 /// Apply a multi-call step only when `option` is `Some` — the
108 /// conditional-composition form for fragments that need more than one
109 /// builder call (a [`bind`](Self::bind) + [`filter`](Self::filter)
110 /// pair, or an operator chosen at runtime). `None` passes the clause
111 /// through untouched, so a ladder of `apply_if`s reads as a
112 /// declarative optional-predicate list:
113 ///
114 /// ```
115 /// # use arcadedb_protocol::FilterClause;
116 /// let filter = FilterClause::new()
117 /// .apply_if(Some(75), |f, min| {
118 /// f.bind("band_min", min).filter("reviews >= :band_min")
119 /// })
120 /// .apply_if(None::<i32>, |f, max| f.lte("reviews", max));
121 /// assert_eq!(filter.sql(), "reviews >= :band_min");
122 /// assert!(filter.clone().into_params().0.contains_key("band_min"));
123 /// ```
124 pub fn apply_if<T>(self, option: Option<T>, f: impl FnOnce(Self, T) -> Self) -> Self {
125 match option {
126 Some(v) => f(self, v),
127 None => self,
128 }
129 }
130
131 /// Register a param WITHOUT emitting a fragment — for placeholders
132 /// referenced elsewhere in the statement.
133 pub fn bind(mut self, name: &str, value: impl IntoGrpcValue) -> Self {
134 self.params.insert(name.to_string(), value.into_value());
135 self
136 }
137
138 /// `col = :col`.
139 pub fn eq(mut self, col: &str, value: impl IntoGrpcValue) -> Self {
140 let c = col.to_string();
141 let name = self.param_name(&c);
142 self.frags.push(format!("{c} = :{name}"));
143 self.params.insert(name, value.into_value());
144 self
145 }
146
147 /// `col <> :col__ne`.
148 pub fn ne(self, col: &str, value: impl IntoGrpcValue) -> Self {
149 self.tagged(col, "ne", "<>", value)
150 }
151
152 /// `col < :col__lt`.
153 pub fn lt(self, col: &str, value: impl IntoGrpcValue) -> Self {
154 self.tagged(col, "lt", "<", value)
155 }
156
157 /// `col <= :col__lte`.
158 pub fn lte(self, col: &str, value: impl IntoGrpcValue) -> Self {
159 self.tagged(col, "lte", "<=", value)
160 }
161
162 /// `col > :col__gt`.
163 pub fn gt(self, col: &str, value: impl IntoGrpcValue) -> Self {
164 self.tagged(col, "gt", ">", value)
165 }
166
167 /// `col >= :col__gte`.
168 pub fn gte(self, col: &str, value: impl IntoGrpcValue) -> Self {
169 self.tagged(col, "gte", ">=", value)
170 }
171
172 /// `col BETWEEN :col__from AND :col__to`.
173 pub fn between(mut self, col: &str, from: impl IntoGrpcValue, to: impl IntoGrpcValue) -> Self {
174 let c = col.to_string();
175 let name = self.param_name(&format!("{c}__from"));
176 let to_name = self.param_name(&format!("{c}__to"));
177 self.frags
178 .push(format!("{c} BETWEEN :{name} AND :{to_name}"));
179 self.params.insert(name, from.into_value());
180 self.params.insert(to_name, to.into_value());
181 self
182 }
183
184 /// `col IS NULL` (no param).
185 pub fn is_null(mut self, col: &str) -> Self {
186 self.frags.push(format!("{col} IS NULL"));
187 self
188 }
189
190 /// `col IS NOT NULL` (no param).
191 pub fn is_not_null(mut self, col: &str) -> Self {
192 self.frags.push(format!("{col} IS NOT NULL"));
193 self
194 }
195
196 /// `col IN :col__in` with the values bound as ONE list parameter.
197 pub fn in_list<I>(mut self, col: &str, values: I) -> Self
198 where
199 I: IntoIterator,
200 I::Item: IntoGrpcValue,
201 {
202 let c = col.to_string();
203 let name = self.param_name(&format!("{c}__in"));
204 self.frags.push(format!("{c} IN :{name}"));
205 self.params.insert(
206 name,
207 crate::encode::list_v(values.into_iter().map(IntoGrpcValue::into_value)),
208 );
209 self
210 }
211
212 /// `col NOT IN :col__nin`. Documented NOT to use the index — pair
213 /// with an indexed condition on large types.
214 ///
215 /// History: on an *indexed* property, releases 26.7.1–26.9.0 served the
216 /// IN result set here (ArcadeData/arcadedb#6796). Fixed in 26.9.1.
217 pub fn not_in<I>(mut self, col: &str, values: I) -> Self
218 where
219 I: IntoIterator,
220 I::Item: IntoGrpcValue,
221 {
222 let c = col.to_string();
223 let name = self.param_name(&format!("{c}__nin"));
224 self.frags.push(format!("{c} NOT IN :{name}"));
225 self.params.insert(
226 name,
227 crate::encode::list_v(values.into_iter().map(IntoGrpcValue::into_value)),
228 );
229 self
230 }
231
232 /// `col CONTAINS :col__has` — true when the collection holds the
233 /// bound SCALAR value. For multi-element membership use
234 /// [`contains_all`](Self::contains_all) /
235 /// [`contains_any`](Self::contains_any).
236 pub fn contains(self, col: &str, value: impl IntoGrpcValue) -> Self {
237 self.tagged(col, "has", "CONTAINS", value)
238 }
239
240 /// `col CONTAINSALL :col__all` — every element of the bound collection
241 /// is present in `col`.
242 pub fn contains_all<I>(mut self, col: &str, values: I) -> Self
243 where
244 I: IntoIterator,
245 I::Item: IntoGrpcValue,
246 {
247 let c = col.to_string();
248 let name = self.param_name(&format!("{c}__all"));
249 self.frags.push(format!("{c} CONTAINSALL :{name}"));
250 self.params.insert(
251 name,
252 crate::encode::list_v(values.into_iter().map(IntoGrpcValue::into_value)),
253 );
254 self
255 }
256
257 /// `col CONTAINSANY :col__any` — at least one element of the bound
258 /// collection is present in `col`.
259 pub fn contains_any<I>(mut self, col: &str, values: I) -> Self
260 where
261 I: IntoIterator,
262 I::Item: IntoGrpcValue,
263 {
264 let c = col.to_string();
265 let name = self.param_name(&format!("{c}__any"));
266 self.frags.push(format!("{c} CONTAINSANY :{name}"));
267 self.params.insert(
268 name,
269 crate::encode::list_v(values.into_iter().map(IntoGrpcValue::into_value)),
270 );
271 self
272 }
273
274 /// `NOT (col CONTAINSANY :col__any)` — none of the bound elements
275 /// may be present.
276 pub fn not_contains_any<I>(self, col: &str, values: I) -> Self
277 where
278 I: IntoIterator,
279 I::Item: IntoGrpcValue,
280 {
281 // Emit through the same path so the param name stays identical to
282 // contains_any's, then wrap the just-pushed fragment.
283 let mut this = self.contains_any(col, values);
284 let last = this
285 .frags
286 .last_mut()
287 .expect("contains_any pushed a fragment");
288 *last = format!("NOT ({last})");
289 this
290 }
291
292 /// `col LIKE :col__like` (case-sensitive, `%`/`?` wildcards).
293 pub fn like(self, col: &str, pattern: impl IntoGrpcValue) -> Self {
294 self.tagged(col, "like", "LIKE", pattern)
295 }
296
297 /// `col ILIKE :col__ilike` (case-insensitive `LIKE`).
298 pub fn ilike(self, col: &str, pattern: impl IntoGrpcValue) -> Self {
299 self.tagged(col, "ilike", "ILIKE", pattern)
300 }
301
302 /// The one-flag-per-operator emitter: `{col} {OP} :{col}__{tag}`.
303 fn tagged(mut self, col: &str, tag: &str, op: &str, value: impl IntoGrpcValue) -> Self {
304 let c = col.to_string();
305 let name = self.param_name(&format!("{c}__{tag}"));
306 self.frags.push(format!("{c} {op} :{name}"));
307 self.params.insert(name, value.into_value());
308 self
309 }
310
311 /// Deterministic param name: the base if free, else
312 /// `{base}_2`, `{base}_3`, …
313 fn param_name(&mut self, base: &str) -> String {
314 if !self.params.contains_key(base) {
315 return base.to_string();
316 }
317 for n in 2.. {
318 let candidate = format!("{base}_{n}");
319 if !self.params.contains_key(&candidate) {
320 return candidate;
321 }
322 }
323 unreachable!("u32 sequence exhausts memory first")
324 }
325}