Skip to main content

diesel_aip_160/
lib.rs

1#![doc = include_str!("../README.md")]
2
3pub mod compiler;
4#[cfg(any(feature = "sqlite", feature = "mysql", feature = "postgres"))]
5pub mod diesel_helpers;
6#[cfg(any(feature = "sqlite", feature = "mysql", feature = "postgres"))]
7pub mod native;
8pub mod parser;
9#[cfg(feature = "postgres")]
10#[doc(hidden)]
11pub mod pg_enum;
12#[cfg(any(feature = "sqlite", feature = "mysql", feature = "postgres"))]
13pub mod ranking;
14pub mod search;
15
16pub use compiler::QueryFilter;
17#[cfg(any(feature = "sqlite", feature = "mysql", feature = "postgres"))]
18pub use diesel_helpers::{Backend, FieldAdapter, Predicate, SearchAdapter};
19#[cfg(any(feature = "sqlite", feature = "mysql", feature = "postgres"))]
20pub use ranking::{CompiledQueryFilter, Direction, Ordering, RankingExpression, RankingSignal};
21
22pub use anyhow;
23#[cfg(any(feature = "sqlite", feature = "mysql", feature = "postgres"))]
24pub use diesel;
25pub use diesel_aip_160_derive::{Aip160Filter, Aip160Jsonb, Aip160PgEnum};
26pub use serde_json;
27
28/// Map a filter's first JSONB path segment to its stored JSON key.
29///
30/// Derived structs accept their registered Rust field names. `serde_json::Value`
31/// accepts arbitrary keys. Later segments use stored JSON keys directly.
32#[diagnostic::on_unimplemented(
33    message = "unsupported Aip160Filter field type `{Self}`",
34    label = "use #[aip160(adapter = MyAdapter)] for custom fields, #[aip160(skip)] to exclude it, or derive Aip160Jsonb for a JSONB field"
35)]
36pub trait JsonbPath {
37    /// Return the stored key, or `None` if this field is not registered.
38    fn stored_key(field: &str) -> Option<&str>;
39}
40
41impl JsonbPath for serde_json::Value {
42    fn stored_key(field: &str) -> Option<&str> {
43        Some(field)
44    }
45}
46
47/// Resolve a field name relative to an explicitly registered JSONB column.
48/// The root column returns an empty path; unknown roots or mapped fields return
49/// `None`. The derive supplies the trusted column name.
50pub fn json_path<T: JsonbPath>(field: &str, column: &str) -> Option<Vec<String>> {
51    if field == column {
52        return Some(Vec::new());
53    }
54    let path = field.strip_prefix(column)?.strip_prefix('.')?;
55    let mut parts = path.split('.');
56    let first = T::stored_key(parts.next()?)?;
57    Some(
58        std::iter::once(first)
59            .chain(parts)
60            .map(str::to_owned)
61            .collect(),
62    )
63}
64#[cfg(any(
65    all(feature = "sqlite", feature = "mysql"),
66    all(feature = "sqlite", feature = "postgres"),
67    all(feature = "mysql", feature = "postgres"),
68))]
69compile_error!("enable exactly one of the `sqlite`, `mysql`, or `postgres` features");