dynamodb_expression/condition/
in_.rs

1use core::fmt::{self, Write};
2
3use crate::operand::Operand;
4
5/// Represents a [DynamoDB `IN` condition][1]. True if the value from the
6/// [`Operand`] (the `op` parameter) is equal to any value in the list (the
7/// `items` parameter).
8///
9/// The DynamoDB allows the list to contain up to 100 values. It must have at least 1.
10///
11/// See also: [`Path::in_`]
12///
13/// ```
14/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
15/// use dynamodb_expression::{condition::In, operand::Operand, Path};
16/// # use pretty_assertions::assert_eq;
17///
18/// let condition = "name".parse::<Path>()?.in_(["Jack", "Jill"]);
19/// assert_eq!(r#"name IN ("Jack","Jill")"#, condition.to_string());
20/// #
21/// # Ok(())
22/// # }
23/// ```
24///
25/// [1]: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html#Expressions.OperatorsAndFunctions.Comparators
26/// [`Path::in_`]: crate::path::Path::in_
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct In {
29    pub(crate) op: Operand,
30    pub(crate) items: Vec<Operand>,
31}
32
33impl In {
34    /// Allows for manually creating an `In` instance.
35    ///
36    /// See also: [`Path::in_`]
37    ///
38    /// ```
39    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
40    /// use dynamodb_expression::{condition::In, operand::Operand, Path};
41    /// # use pretty_assertions::assert_eq;
42    ///
43    /// let condition = In::new("name".parse::<Path>()?, ["Jack", "Jill"]);
44    /// assert_eq!(r#"name IN ("Jack","Jill")"#, condition.to_string());
45    /// #
46    /// # Ok(())
47    /// # }
48    /// ```
49    ///
50    /// [1]: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html#Expressions.OperatorsAndFunctions.Comparators
51    /// [`Path::in_`]: crate::path::Path::in_
52    pub fn new<O, I, T>(op: O, items: I) -> Self
53    where
54        O: Into<Operand>,
55        I: IntoIterator<Item = T>,
56        T: Into<Operand>,
57    {
58        Self {
59            op: op.into(),
60            items: items.into_iter().map(Into::into).collect(),
61        }
62    }
63}
64
65impl fmt::Display for In {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        self.op.fmt(f)?;
68        f.write_str(" IN (")?;
69
70        let mut first = true;
71        self.items.iter().try_for_each(|item| {
72            if first {
73                first = false;
74            } else {
75                f.write_char(',')?;
76            }
77
78            item.fmt(f)
79        })?;
80
81        f.write_char(')')
82    }
83}