Skip to content

Commit 107eed8

Browse files
authored
feat: add matches_cql2 (#909)
This might be nice to expose to the CLI later, but for now we'll just add the method. cc @bitner, this was pretty easy! Closes #567
1 parent 19ac653 commit 107eed8

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

crates/core/src/item.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
33
use crate::{Asset, Assets, Bbox, Error, Fields, Link, Result, STAC_VERSION, Version};
44
use chrono::{DateTime, FixedOffset, NaiveDateTime, Utc};
5+
use cql2::Expr;
56
use geojson::{Feature, Geometry, feature::Id};
67
use indexmap::IndexMap;
78
use serde::{Deserialize, Deserializer, Serialize};
@@ -602,6 +603,22 @@ impl Item {
602603
properties,
603604
})
604605
}
606+
607+
/// Returns true if this item matches the given CQL2 expression.
608+
///
609+
/// # Examples
610+
///
611+
/// ```
612+
/// use stac::Item;
613+
///
614+
/// let item = Item::new("an-item");
615+
/// assert!(item.clone().matches_cql2("id = 'an-item'".parse().unwrap()).unwrap());
616+
/// assert!(!item.matches_cql2("id = 'another-item'".parse().unwrap()).unwrap());
617+
/// ```
618+
pub fn matches_cql2(self, expr: Expr) -> Result<bool> {
619+
let result = self.into_flat_item(true)?.matches_cql2(expr)?;
620+
Ok(result)
621+
}
605622
}
606623

607624
impl Assets for Item {
@@ -685,6 +702,15 @@ impl TryFrom<Item> for Feature {
685702
}
686703
}
687704

705+
impl FlatItem {
706+
/// Returns true if the item matches the given CQL2 expression.
707+
pub fn matches_cql2(self, expr: Expr) -> Result<bool> {
708+
let value = serde_json::to_value(self)?;
709+
let result = expr.matches(Some(&value)).map_err(Box::new)?;
710+
Ok(result)
711+
}
712+
}
713+
688714
fn default_stac_version() -> Version {
689715
STAC_VERSION
690716
}
@@ -945,4 +971,19 @@ mod tests {
945971
fn read_invalid_item_datetimes() {
946972
let _: Item = crate::read("data/invalid-datetimes.json").unwrap();
947973
}
974+
975+
#[test]
976+
fn matches_cql2() {
977+
let item = Item::new("an-item");
978+
assert!(
979+
item.clone()
980+
.matches_cql2("id = 'an-item'".parse().unwrap())
981+
.unwrap()
982+
);
983+
assert!(
984+
!item
985+
.matches_cql2("id = 'another-item'".parse().unwrap())
986+
.unwrap()
987+
);
988+
}
948989
}

0 commit comments

Comments
 (0)