macro_rules! query {
($($field:ident).+ > $value:expr) => { ... };
($($field:ident).+ >= $value:expr) => { ... };
($($field:ident).+ < $value:expr) => { ... };
($($field:ident).+ <= $value:expr) => { ... };
($($field:ident).+ == null) => { ... };
($($field:ident).+ != null) => { ... };
($($field:ident).+ == $value:expr) => { ... };
($($field:ident).+ != $value:expr) => { ... };
($($field:ident).+) => { ... };
($($field:ident).+, $closure:expr) => { ... };
}Expand description
Creates a query from Rust-like logical syntax.
Basic Examples
For simple equality and ordering queries, you can just write the path to the field as you would in Rust or JavaScript, separated by dots, then an operator, and then a value. This uses the field names in the JSON serialization instead of those in the Rust struct.
query!(age >= 18) // `age` field >= 18
query!(coordinates.lat > 0.0) // `lat` field of `coordinates` > 0.0, e.g. above equator
query!(country == "UK") // `country` field == "UK"
query!(price < 10) | query!(discounted) // `price` field < 10 or `discounted` field == trueYou’ll notice that queries are combined using bitwise operators outside of the macro.
This is because the macro is currently not able to parse && and ||, but this will hopefully change in the future.
Advanced Examples
For more complex queries, you can use a closure to define the predicate. You still need to specify the field using the dot syntax for optimisation purposes, as shown below.
// Check whether the field `dob.year` is a leap year.
// https://en.wikipedia.org/wiki/Leap_year
query!(dob.year, |year| year
.as_number()
.map(|y| (y as usize % 4 == 0 && y as usize % 100 != 0) || y as usize % 400 == 0)
.unwrap_or(false));