influx_client/flux/
read_query.rs

1use std::fmt::Display;
2
3use super::functions::{Filter, Limit, Range, Sort};
4
5/// Use this struct to read from a bucket.
6pub struct ReadQuery<'a> {
7    bucket: &'a str,
8    range: Option<String>,
9    filters: Vec<String>,
10    sort: Option<String>,
11    limit: Option<String>,
12}
13
14impl<'a> ReadQuery<'a> {
15    pub fn new(bucket: &'a str) -> Self {
16        Self {
17            bucket,
18            range: None,
19            filters: Vec::new(),
20            sort: None,
21            limit: None,
22        }
23    }
24
25    /// Only read data in a certain time range
26    pub fn range(mut self, range: Range) -> Self {
27        self.range.replace(range.to_string());
28        self
29    }
30
31    /// Filter the data based on its value
32    pub fn filter<T: Filter>(mut self, kind: T) -> Self {
33        self.filters.push(kind.to_string());
34        self
35    }
36
37    /// Sort the data by the value of the given columns
38    pub fn sort(mut self, sort: Sort) -> Self {
39        self.sort.replace(sort.to_string());
40        self
41    }
42
43    /// Only read a given number of data points
44    pub fn limit(mut self, limit: Limit) -> Self {
45        self.limit.replace(limit.to_string());
46        self
47    }
48}
49
50impl<'a> Display for ReadQuery<'a> {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        write!(
53            f,
54            "from(bucket: \"{}\"){}{}{}{}",
55            self.bucket,
56            if let Some(range) = &self.range {
57                format!(" |> {range}")
58            } else {
59                String::new()
60            },
61            if !&self.filters.is_empty() {
62                format!(" |> {}", self.filters.join(" |> "))
63            } else {
64                String::new()
65            },
66            if let Some(sort) = &self.sort {
67                format!(" |> {sort}")
68            } else {
69                String::new()
70            },
71            if let Some(limit) = &self.limit {
72                format!(" |> {limit}")
73            } else {
74                String::new()
75            }
76        )
77    }
78}