Skip to main content

QueryItem

Struct QueryItem 

Source
pub struct QueryItem { /* private fields */ }
Expand description

One clause of a Query.

An event matches an item when both hold:

  • its type is one of types — OR semantics, and an empty types matches any type;
  • its tags contain all of tags — AND semantics, and an empty tags matches any tags.

At least one of the two must be non-empty; an item constraining neither would match everything, which is Query::all’s job.

§Examples

use happenstance_core::{QueryItem, Tags};

// "Any StudentSubscribed or StudentUnsubscribed event for course c1."
let item = QueryItem::new(
    ["StudentSubscribed", "StudentUnsubscribed"],
    Tags::from_pairs([("course", "c1")])?,
)?;

assert_eq!(item.types().len(), 2);

Implementations§

Source§

impl QueryItem

Source

pub fn new<T>( types: impl IntoIterator<Item = T>, tags: Tags, ) -> Result<Self, InvalidQuery>

Creates a query item.

Types are deduplicated and sorted so that two items expressing the same constraint compare equal.

§Errors

Returns InvalidQuery::UnconstrainedItem if both types and tags are empty, or InvalidQuery::EventType if a type string is invalid.

The InvalidQuery: From<T::Error> bound is what lets this accept both &str (fallible conversion) and an already-built EventType (infallible), rather than forcing callers into one or the other.

Source

pub fn of( first: EventType, rest: impl IntoIterator<Item = EventType>, tags: Tags, ) -> Self

Creates an item from at least one type the caller already holds.

Total: it returns QueryItem, not a Result. new has two ways to fail, and neither can reach this signature. A built EventType has already been validated, and a separate first parameter means the item always constrains at least one type, so it can never be the unconstrained item new refuses. Equal inputs produce == items through either constructor, because both share one sort and dedup.

Reach for new instead when the types are strings, or arrive as a sequence whose length you do not know, and for of_types when there are also no tags. Both validate and can refuse, which is why they return a Result. Splitting off the head is how “at least one” becomes a fact of the signature here: a slice or iterator parameter says nothing about its length, so a total constructor over one would have to panic or accept the empty item (ADR-0069).

§Examples
use happenstance_core::{EventType, QueryItem, Tags};

const COURSE_DEFINED: EventType = EventType::from_static("CourseDefined");
let tags = Tags::from_pairs([("course", "c1")])?;

// No further types, and no `?` on the item.
let item = QueryItem::of(COURSE_DEFINED, [], tags);

assert_eq!(item.types(), [COURSE_DEFINED]);
Source

pub fn of_types<T>( types: impl IntoIterator<Item = T>, ) -> Result<Self, InvalidQuery>

Creates an item constrained only by type.

§Errors

Returns InvalidQuery::UnconstrainedItem if types is empty, or InvalidQuery::EventType if a type string is invalid.

Source

pub fn tagged(tags: Tags) -> Result<Self, InvalidQuery>

Creates an item constrained only by tags.

§Errors

Returns InvalidQuery::UnconstrainedItem if tags is empty.

Source

pub fn types(&self) -> &[EventType]

The types this item accepts, sorted. Empty means “any type”.

Examples found in repository?
examples/handles-and-quotas/src/main.rs (line 885)
879fn print_boundary<B: Boundary>(boundary: &B) -> Result<()> {
880    let query = boundary.query()?;
881
882    match query.items() {
883        Some(items) => {
884            for item in items {
885                let types: Vec<&str> = item.types().iter().map(EventType::as_str).collect();
886                println!("      {} where {:?}", types.join(" | "), item.tags());
887            }
888        }
889        // Unreachable for a well-formed model, and spelled rather than
890        // `unwrap`ped: `Query::All` is what a boundary constraining neither
891        // types nor tags would produce, and an empty `EVENT_TYPES` is already
892        // a compile error.
893        None => println!("      the whole log"),
894    }
895
896    Ok(())
897}
Source

pub fn tags(&self) -> &Tags

The tags an event must carry. Empty means “any tags”.

Examples found in repository?
examples/handles-and-quotas/src/main.rs (line 886)
879fn print_boundary<B: Boundary>(boundary: &B) -> Result<()> {
880    let query = boundary.query()?;
881
882    match query.items() {
883        Some(items) => {
884            for item in items {
885                let types: Vec<&str> = item.types().iter().map(EventType::as_str).collect();
886                println!("      {} where {:?}", types.join(" | "), item.tags());
887            }
888        }
889        // Unreachable for a well-formed model, and spelled rather than
890        // `unwrap`ped: `Query::All` is what a boundary constraining neither
891        // types nor tags would produce, and an empty `EVENT_TYPES` is already
892        // a compile error.
893        None => println!("      the whole log"),
894    }
895
896    Ok(())
897}
Source

pub fn matches(&self, event_type: &EventType, tags: &Tags) -> bool

Whether an event with this type and these tags matches.

Trait Implementations§

Source§

impl Clone for QueryItem

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for QueryItem

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for QueryItem

Available on crate feature serde only.
Source§

fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Eq for QueryItem

Source§

impl PartialEq for QueryItem

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Serialize for QueryItem

Available on crate feature serde only.
Source§

fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for QueryItem

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.