1#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
2pub mod builder;
3pub mod errors;
4pub mod filter;
5pub mod limits;
6pub(crate) mod odata_filters;
7mod odata_parse;
8pub mod page;
9pub mod pagination;
10pub mod problem_mapping;
11pub mod schema;
12
13pub use builder::QueryBuilder;
14pub use limits::ODataLimits;
15pub use page::{Page, PageInfo};
16pub use pagination::{normalize_filter_for_hash, short_filter_hash};
17pub use schema::{FieldRef, Schema};
18
19pub mod ast {
20 use bigdecimal::BigDecimal;
21 use chrono::{DateTime, NaiveDate, NaiveTime, Utc};
22 use uuid::Uuid;
23
24 #[derive(Clone, Debug)]
25 pub enum Expr {
26 And(Box<Expr>, Box<Expr>),
27 Or(Box<Expr>, Box<Expr>),
28 Not(Box<Expr>),
29 Compare(Box<Expr>, CompareOperator, Box<Expr>),
30 In(Box<Expr>, Vec<Expr>),
31 Function(String, Vec<Expr>),
32 Identifier(String),
33 Value(Value),
34 }
35
36 impl Expr {
37 #[must_use]
45 pub fn and(self, other: Expr) -> Expr {
46 Expr::And(Box::new(self), Box::new(other))
47 }
48
49 #[must_use]
51 pub fn or(self, other: Expr) -> Expr {
52 Expr::Or(Box::new(self), Box::new(other))
53 }
54
55 #[must_use]
57 #[allow(clippy::should_implement_trait)]
58 pub fn not(self) -> Expr {
59 !self
60 }
61 }
62
63 impl std::ops::Not for Expr {
64 type Output = Expr;
65
66 fn not(self) -> Self::Output {
67 Expr::Not(Box::new(self))
68 }
69 }
70
71 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
72 pub enum CompareOperator {
73 Eq,
74 Ne,
75 Gt,
76 Ge,
77 Lt,
78 Le,
79 }
80
81 #[derive(Clone, Debug)]
82 pub enum Value {
83 Null,
84 Bool(bool),
85 Number(BigDecimal),
86 Uuid(Uuid),
87 DateTime(DateTime<Utc>),
88 Date(NaiveDate),
89 Time(NaiveTime),
90 String(String),
91 }
92
93 impl std::fmt::Display for Value {
94 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95 match self {
96 Value::Null => write!(f, "null"),
97 Value::Bool(_) => write!(f, "bool"),
98 Value::Number(_) => write!(f, "number"),
99 Value::Uuid(_) => write!(f, "uuid"),
100 Value::DateTime(_) => write!(f, "datetime"),
101 Value::Date(_) => write!(f, "date"),
102 Value::Time(_) => write!(f, "time"),
103 Value::String(_) => write!(f, "string"),
104 }
105 }
106 }
107}
108
109#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
111pub enum SortDir {
112 #[serde(rename = "asc")]
113 Asc,
114 #[serde(rename = "desc")]
115 Desc,
116}
117
118impl SortDir {
119 #[must_use]
121 pub fn reverse(self) -> Self {
122 match self {
123 SortDir::Asc => SortDir::Desc,
124 SortDir::Desc => SortDir::Asc,
125 }
126 }
127}
128
129#[derive(Clone, Debug)]
130pub struct OrderKey {
131 pub field: String,
132 pub dir: SortDir,
133}
134
135#[derive(Clone, Debug, Default)]
136#[must_use]
137pub struct ODataOrderBy(pub Vec<OrderKey>);
138
139impl ODataOrderBy {
140 pub fn empty() -> Self {
141 Self(vec![])
142 }
143
144 #[must_use]
145 pub fn is_empty(&self) -> bool {
146 self.0.is_empty()
147 }
148
149 #[must_use]
151 pub fn to_signed_tokens(&self) -> String {
152 self.0
153 .iter()
154 .map(|k| {
155 if matches!(k.dir, SortDir::Asc) {
156 format!("+{}", k.field)
157 } else {
158 format!("-{}", k.field)
159 }
160 })
161 .collect::<Vec<_>>()
162 .join(",")
163 }
164
165 pub fn from_signed_tokens(signed: &str) -> Result<Self, Error> {
171 let mut out = Vec::new();
172 for seg in signed.split(',') {
173 let seg = seg.trim();
174 if seg.is_empty() {
175 continue;
176 }
177 let (dir, name) = match seg.as_bytes()[0] {
178 b'+' => (SortDir::Asc, &seg[1..]),
179 b'-' => (SortDir::Desc, &seg[1..]),
180 _ => (SortDir::Asc, seg), };
182 if name.is_empty() {
183 return Err(Error::InvalidOrderByField(seg.to_owned()));
184 }
185 out.push(OrderKey {
186 field: name.to_owned(),
187 dir,
188 });
189 }
190 if out.is_empty() {
191 return Err(Error::InvalidOrderByField("empty order".into()));
192 }
193 Ok(ODataOrderBy(out))
194 }
195
196 #[must_use]
198 pub fn equals_signed_tokens(&self, signed: &str) -> bool {
199 let parse = |t: &str| -> Option<(String, SortDir)> {
200 let t = t.trim();
201 if t.is_empty() {
202 return None;
203 }
204 let (dir, name) = match t.as_bytes()[0] {
205 b'+' => (SortDir::Asc, &t[1..]),
206 b'-' => (SortDir::Desc, &t[1..]),
207 _ => (SortDir::Asc, t),
208 };
209 if name.is_empty() {
210 return None;
211 }
212 Some((name.to_owned(), dir))
213 };
214 let theirs: Vec<_> = signed.split(',').filter_map(parse).collect();
215 if theirs.len() != self.0.len() {
216 return false;
217 }
218 self.0
219 .iter()
220 .zip(theirs.iter())
221 .all(|(a, (n, d))| a.field == *n && a.dir == *d)
222 }
223
224 pub fn ensure_tiebreaker(mut self, tiebreaker: &str, dir: SortDir) -> Self {
226 if !self.0.iter().any(|k| k.field == tiebreaker) {
227 self.0.push(OrderKey {
228 field: tiebreaker.to_owned(),
229 dir,
230 });
231 }
232 self
233 }
234
235 pub fn reverse_directions(mut self) -> Self {
237 for key in &mut self.0 {
238 key.dir = key.dir.reverse();
239 }
240 self
241 }
242}
243
244impl std::fmt::Display for ODataOrderBy {
246 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
247 if self.0.is_empty() {
248 return write!(f, "(none)");
249 }
250
251 let formatted: Vec<String> = self
252 .0
253 .iter()
254 .map(|key| {
255 let dir_str = match key.dir {
256 SortDir::Asc => "asc",
257 SortDir::Desc => "desc",
258 };
259 format!("{} {}", key.field, dir_str)
260 })
261 .collect();
262
263 write!(f, "{}", formatted.join(", "))
264 }
265}
266
267#[derive(thiserror::Error, Debug, Clone)]
282pub enum Error {
283 #[error("invalid $filter: {0}")]
285 InvalidFilter(String),
286
287 #[error("unsupported $orderby field: {0}")]
289 InvalidOrderByField(String),
290
291 #[error("ORDER_MISMATCH")]
293 OrderMismatch,
294
295 #[error("FILTER_MISMATCH")]
296 FilterMismatch,
297
298 #[error("INVALID_CURSOR")]
299 InvalidCursor,
300
301 #[error("INVALID_LIMIT")]
302 InvalidLimit,
303
304 #[error("ORDER_WITH_CURSOR")]
305 OrderWithCursor,
306
307 #[error("invalid cursor: invalid base64url encoding")]
309 CursorInvalidBase64,
310
311 #[error("invalid cursor: malformed JSON")]
312 CursorInvalidJson,
313
314 #[error("invalid cursor: unsupported version")]
315 CursorInvalidVersion,
316
317 #[error("invalid cursor: empty or invalid keys")]
318 CursorInvalidKeys,
319
320 #[error("invalid cursor: empty or invalid fields")]
321 CursorInvalidFields,
322
323 #[error("invalid cursor: invalid sort direction")]
324 CursorInvalidDirection,
325
326 #[error("database error: {0}")]
328 Db(String),
329
330 #[error("OData parsing unavailable: {0}")]
332 ParsingUnavailable(&'static str),
333}
334
335pub fn validate_cursor_against(
341 cursor: &CursorV1,
342 effective_order: &ODataOrderBy,
343 effective_filter_hash: Option<&str>,
344) -> Result<(), Error> {
345 if !effective_order.equals_signed_tokens(&cursor.s) {
346 return Err(Error::OrderMismatch);
347 }
348 if let (Some(h), Some(cf)) = (effective_filter_hash, cursor.f.as_deref())
349 && h != cf
350 {
351 return Err(Error::FilterMismatch);
352 }
353 Ok(())
354}
355
356#[derive(Clone, Debug)]
358pub struct CursorV1 {
359 pub k: Vec<String>,
360 pub o: SortDir,
361 pub s: String,
362 pub f: Option<String>,
363 pub d: String, }
365
366impl CursorV1 {
367 pub fn encode(&self) -> serde_json::Result<String> {
372 #[derive(serde::Serialize)]
373 struct Wire<'a> {
374 v: u8,
375 k: &'a [String],
376 o: &'a str,
377 s: &'a str,
378 #[serde(skip_serializing_if = "Option::is_none")]
379 f: &'a Option<String>,
380 d: &'a str,
381 }
382 let o = match self.o {
383 SortDir::Asc => "asc",
384 SortDir::Desc => "desc",
385 };
386 let w = Wire {
387 v: 1,
388 k: &self.k,
389 o,
390 s: &self.s,
391 f: &self.f,
392 d: &self.d,
393 };
394 serde_json::to_vec(&w).map(|x| base64_url::encode(&x))
395 }
396
397 pub fn decode(token: &str) -> Result<Self, Error> {
405 #[derive(serde::Deserialize)]
406 struct Wire {
407 v: u8,
408 k: Vec<String>,
409 o: String,
410 s: String,
411 #[serde(default)]
412 f: Option<String>,
413 #[serde(default = "default_direction")]
414 d: String,
415 }
416
417 fn default_direction() -> String {
418 "fwd".to_owned()
419 }
420
421 let bytes = base64_url::decode(token).map_err(|_| Error::CursorInvalidBase64)?;
422 let w: Wire = serde_json::from_slice(&bytes).map_err(|_| Error::CursorInvalidJson)?;
423 if w.v != 1 {
424 return Err(Error::CursorInvalidVersion);
425 }
426 let o = match w.o.as_str() {
427 "asc" => SortDir::Asc,
428 "desc" => SortDir::Desc,
429 _ => return Err(Error::CursorInvalidDirection),
430 };
431 if w.k.is_empty() {
432 return Err(Error::CursorInvalidKeys);
433 }
434 if w.s.trim().is_empty() {
435 return Err(Error::CursorInvalidFields);
436 }
437 if w.d != "fwd" && w.d != "bwd" {
439 return Err(Error::CursorInvalidDirection);
440 }
441 Ok(CursorV1 {
442 k: w.k,
443 o,
444 s: w.s,
445 f: w.f,
446 d: w.d,
447 })
448 }
449}
450
451mod base64_url {
453 use base64::Engine;
454
455 pub fn encode(bytes: &[u8]) -> String {
456 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)
457 }
458
459 pub fn decode(s: &str) -> Result<Vec<u8>, base64::DecodeError> {
460 base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(s)
461 }
462}
463
464#[derive(Clone, Debug, Default)]
466#[must_use]
467pub struct ODataQuery {
468 pub filter: Option<Box<ast::Expr>>,
469 pub order: ODataOrderBy,
470 pub limit: Option<u64>,
471 pub cursor: Option<CursorV1>,
472 pub filter_hash: Option<String>,
473 pub select: Option<Vec<String>>,
474}
475
476impl ODataQuery {
477 pub fn new() -> Self {
478 Self::default()
479 }
480
481 pub fn with_filter(mut self, expr: ast::Expr) -> Self {
482 self.filter = Some(Box::new(expr));
483 self
484 }
485
486 pub fn with_order(mut self, order: ODataOrderBy) -> Self {
487 self.order = order;
488 self
489 }
490
491 pub fn with_limit(mut self, limit: u64) -> Self {
492 self.limit = Some(limit);
493 self
494 }
495
496 pub fn with_cursor(mut self, cursor: CursorV1) -> Self {
497 self.cursor = Some(cursor);
498 self
499 }
500
501 pub fn with_filter_hash(mut self, hash: String) -> Self {
502 self.filter_hash = Some(hash);
503 self
504 }
505
506 pub fn with_select(mut self, fields: Vec<String>) -> Self {
507 self.select = Some(fields);
508 self
509 }
510
511 #[must_use]
513 pub fn filter(&self) -> Option<&ast::Expr> {
514 self.filter.as_deref()
515 }
516
517 #[must_use]
519 pub fn has_filter(&self) -> bool {
520 self.filter.is_some()
521 }
522
523 #[must_use]
525 pub fn into_filter(self) -> Option<ast::Expr> {
526 self.filter.map(|b| *b)
527 }
528
529 #[must_use]
531 pub fn has_select(&self) -> bool {
532 self.select.is_some()
533 }
534
535 #[must_use]
537 pub fn selected_fields(&self) -> Option<&[String]> {
538 self.select.as_deref()
539 }
540}
541
542impl From<Option<ast::Expr>> for ODataQuery {
543 fn from(opt: Option<ast::Expr>) -> Self {
544 match opt {
545 Some(e) => Self::default().with_filter(e),
546 None => Self::default(),
547 }
548 }
549}
550
551#[cfg(test)]
552mod odata_parse_tests;
553mod tests;
554
555mod convert_odata_filters {
556 use super::ast::{CompareOperator, Expr, Value};
557 use crate::odata_filters as od;
558
559 impl From<od::CompareOperator> for CompareOperator {
560 fn from(op: od::CompareOperator) -> Self {
561 use od::CompareOperator::{
562 Equal, GreaterOrEqual, GreaterThan, LessOrEqual, LessThan, NotEqual,
563 };
564 match op {
565 Equal => CompareOperator::Eq,
566 NotEqual => CompareOperator::Ne,
567 GreaterThan => CompareOperator::Gt,
568 GreaterOrEqual => CompareOperator::Ge,
569 LessThan => CompareOperator::Lt,
570 LessOrEqual => CompareOperator::Le,
571 }
572 }
573 }
574
575 impl From<od::Value> for Value {
576 fn from(v: od::Value) -> Self {
577 match v {
578 od::Value::Null => Value::Null,
579 od::Value::Bool(b) => Value::Bool(b),
580 od::Value::Number(n) => Value::Number(n),
581 od::Value::Uuid(u) => Value::Uuid(u),
582 od::Value::DateTime(dt) => Value::DateTime(dt),
583 od::Value::Date(d) => Value::Date(d),
584 od::Value::Time(t) => Value::Time(t),
585 od::Value::String(s) => Value::String(s),
586 }
587 }
588 }
589
590 impl From<od::Expr> for Expr {
591 fn from(e: od::Expr) -> Self {
592 use od::Expr::{And, Compare, Function, Identifier, In, Not, Or, Value};
593 match e {
594 And(a, b) => Expr::And(Box::new((*a).into()), Box::new((*b).into())),
595 Or(a, b) => Expr::Or(Box::new((*a).into()), Box::new((*b).into())),
596 Not(x) => Expr::Not(Box::new((*x).into())),
597 Compare(l, op, r) => {
598 Expr::Compare(Box::new((*l).into()), op.into(), Box::new((*r).into()))
599 }
600 In(l, list) => Expr::In(
601 Box::new((*l).into()),
602 list.into_iter().map(Into::into).collect(),
603 ),
604 Function(n, args) => Expr::Function(n, args.into_iter().map(Into::into).collect()),
605 Identifier(s) => Expr::Identifier(s),
606 Value(v) => Expr::Value(v.into()),
607 }
608 }
609 }
610}
611
612#[derive(Clone, Debug)]
614pub struct ParsedFilter {
615 expr: ast::Expr,
616 node_count: usize,
617}
618
619impl ParsedFilter {
620 #[must_use]
622 pub fn as_expr(&self) -> &ast::Expr {
623 &self.expr
624 }
625
626 #[must_use]
628 pub fn into_expr(self) -> ast::Expr {
629 self.expr
630 }
631
632 #[must_use]
634 pub fn node_count(&self) -> usize {
635 self.node_count
636 }
637}
638
639pub fn parse_filter_string(raw: &str) -> Result<ParsedFilter, Error> {
654 use crate::odata_filters as od;
655
656 fn count_ast_nodes(e: &od::Expr) -> usize {
658 use od::Expr::{And, Compare, Function, Identifier, In, Not, Or, Value};
659 match e {
660 Value(_) | Identifier(_) => 1,
661 Not(x) => 1 + count_ast_nodes(x),
662 And(a, b) | Or(a, b) | Compare(a, _, b) => 1 + count_ast_nodes(a) + count_ast_nodes(b),
663 In(a, list) => 1 + count_ast_nodes(a) + list.iter().map(count_ast_nodes).sum::<usize>(),
664 Function(_, args) => 1 + args.iter().map(count_ast_nodes).sum::<usize>(),
665 }
666 }
667
668 let ast_src = od::parse_str(raw).map_err(|e| Error::InvalidFilter(format!("{e}")))?;
669
670 let node_count = count_ast_nodes(&ast_src);
671 let expr: ast::Expr = ast_src.into();
672
673 Ok(ParsedFilter { expr, node_count })
674}