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