1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
//! Write Query Builder returned by Query::write_query
//!
//! Can only be instantiated by using Query::write_query

use crate::query::line_proto_term::LineProtoTerm;
use crate::query::{QueryType, ValidQuery};
use crate::{Error, Query, Timestamp};
use std::fmt::{Display, Formatter};

pub trait WriteType {
    fn add_to(self, tag: String, fields_or_tags: &mut Vec<(String, Type)>);
}

impl<T: Into<Type>> WriteType for T {
    fn add_to(self, tag: String, fields_or_tags: &mut Vec<(String, Type)>) {
        let val: Type = self.into();
        fields_or_tags.push((tag, val));
    }
}

impl<T: Into<Type>> WriteType for Option<T> {
    fn add_to(self, tag: String, fields_or_tags: &mut Vec<(String, Type)>) {
        if let Some(val) = self {
            val.add_to(tag, fields_or_tags);
        }
    }
}

/// Internal Representation of a Write query that has not yet been built
#[derive(Debug, Clone)]
pub struct WriteQuery {
    fields: Vec<(String, Type)>,
    tags: Vec<(String, Type)>,
    measurement: String,
    timestamp: Timestamp,
}

impl WriteQuery {
    /// Creates a new [`WriteQuery`](crate::query::write_query::WriteQuery)
    #[must_use = "Creating a query is pointless unless you execute it"]
    pub fn new<S>(timestamp: Timestamp, measurement: S) -> Self
    where
        S: Into<String>,
    {
        WriteQuery {
            fields: vec![],
            tags: vec![],
            measurement: measurement.into(),
            timestamp,
        }
    }

    /// Adds a field to the [`WriteQuery`](crate::WriteQuery)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use influxdb::{Query, Timestamp};
    /// use influxdb::InfluxDbWriteable;
    ///
    /// Timestamp::Nanoseconds(0).into_query("measurement").add_field("field1", 5).build();
    /// ```
    #[must_use = "Creating a query is pointless unless you execute it"]
    pub fn add_field<S, F>(mut self, field: S, value: F) -> Self
    where
        S: Into<String>,
        F: WriteType,
    {
        value.add_to(field.into(), &mut self.fields);
        self
    }

    /// Adds a tag to the [`WriteQuery`](crate::WriteQuery)
    ///
    /// Please note that a [`WriteQuery`](crate::WriteQuery) requires at least one field. Composing a query with
    /// only tags will result in a failure building the query.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use influxdb::{Query, Timestamp};
    /// use influxdb::InfluxDbWriteable;
    ///
    /// Timestamp::Nanoseconds(0)
    ///     .into_query("measurement")
    ///     .add_tag("field1", 5); // calling `.build()` now would result in a `Err(Error::InvalidQueryError)`
    /// ```
    #[must_use = "Creating a query is pointless unless you execute it"]
    pub fn add_tag<S, I>(mut self, tag: S, value: I) -> Self
    where
        S: Into<String>,
        I: WriteType,
    {
        value.add_to(tag.into(), &mut self.tags);
        self
    }

    pub fn get_precision(&self) -> String {
        let modifier = match self.timestamp {
            Timestamp::Nanoseconds(_) => "ns",
            Timestamp::Microseconds(_) => "u",
            Timestamp::Milliseconds(_) => "ms",
            Timestamp::Seconds(_) => "s",
            Timestamp::Minutes(_) => "m",
            Timestamp::Hours(_) => "h",
        };
        modifier.to_string()
    }
}

#[derive(Debug, Clone)]
pub enum Type {
    Boolean(bool),
    Float(f64),
    SignedInteger(i64),
    UnsignedInteger(u64),
    Text(String),
}

impl Display for Type {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        use Type::*;

        match self {
            Boolean(x) => write!(f, "{}", x),
            Float(x) => write!(f, "{}", x),
            SignedInteger(x) => write!(f, "{}", x),
            UnsignedInteger(x) => write!(f, "{}", x),
            Text(text) => write!(f, "{text}", text = text),
        }
    }
}

macro_rules! from_impl {
        ( $variant:ident => $( $typ:ident ),+ ) => (
                $(
                    impl From<$typ> for Type {
                        fn from(b: $typ) -> Self {
                            Type::$variant(b.into())
                        }
                    }
                )+
        )
}
from_impl! {Boolean => bool}
from_impl! {Float => f32, f64}
from_impl! {SignedInteger => i8, i16, i32, i64}
from_impl! {UnsignedInteger => u8, u16, u32, u64}
from_impl! {Text => String}
impl From<&str> for Type {
    fn from(b: &str) -> Self {
        Type::Text(b.into())
    }
}
impl<T> From<&T> for Type
where
    T: Copy + Into<Type>,
{
    fn from(t: &T) -> Self {
        (*t).into()
    }
}

impl Query for WriteQuery {
    fn build(&self) -> Result<ValidQuery, Error> {
        if self.fields.is_empty() {
            return Err(Error::InvalidQueryError {
                error: "fields cannot be empty".to_string(),
            });
        }

        let mut tags = self
            .tags
            .iter()
            .map(|(tag, value)| {
                format!(
                    "{tag}={value}",
                    tag = LineProtoTerm::TagKey(tag).escape(),
                    value = LineProtoTerm::TagValue(value).escape(),
                )
            })
            .collect::<Vec<String>>()
            .join(",");

        if !tags.is_empty() {
            tags.insert(0, ',');
        }
        let fields = self
            .fields
            .iter()
            .map(|(field, value)| {
                format!(
                    "{field}={value}",
                    field = LineProtoTerm::FieldKey(field).escape(),
                    value = LineProtoTerm::FieldValue(value).escape(),
                )
            })
            .collect::<Vec<String>>()
            .join(",");

        Ok(ValidQuery(format!(
            "{measurement}{tags} {fields} {time}",
            measurement = LineProtoTerm::Measurement(&self.measurement).escape(),
            tags = tags,
            fields = fields,
            time = self.timestamp
        )))
    }

    fn get_type(&self) -> QueryType {
        QueryType::WriteQuery(self.get_precision())
    }
}

impl Query for Vec<WriteQuery> {
    fn build(&self) -> Result<ValidQuery, Error> {
        let mut qlines = Vec::new();

        for q in self {
            let valid_query = q.build()?;
            qlines.push(valid_query.0);
        }

        Ok(ValidQuery(qlines.join("\n")))
    }

    fn get_type(&self) -> QueryType {
        QueryType::WriteQuery(
            self.get(0)
                .map(|q| q.get_precision())
                // use "ms" as placeholder if query is empty
                .unwrap_or_else(|| "ms".to_owned()),
        )
    }
}

#[cfg(test)]
mod tests {
    use crate::query::{InfluxDbWriteable, Query, Timestamp};

    #[test]
    fn test_write_builder_empty_query() {
        let query = Timestamp::Hours(5)
            .into_query("marina_3".to_string())
            .build();

        assert!(query.is_err(), "Query was not empty");
    }

    #[test]
    fn test_write_builder_single_field() {
        let query = Timestamp::Hours(11)
            .into_query("weather".to_string())
            .add_field("temperature", 82)
            .build();

        assert!(query.is_ok(), "Query was empty");
        assert_eq!(query.unwrap(), "weather temperature=82i 11");
    }

    #[test]
    fn test_write_builder_multiple_fields() {
        let query = Timestamp::Hours(11)
            .into_query("weather".to_string())
            .add_field("temperature", 82)
            .add_field("wind_strength", 3.7)
            .build();

        assert!(query.is_ok(), "Query was empty");
        assert_eq!(
            query.unwrap(),
            "weather temperature=82i,wind_strength=3.7 11"
        );
    }

    #[test]
    fn test_write_builder_optional_fields() {
        let query = Timestamp::Hours(11)
            .into_query("weather".to_string())
            .add_field("temperature", 82u64)
            .add_tag("wind_strength", <Option<u64>>::None)
            .build();

        assert!(query.is_ok(), "Query was empty");
        assert_eq!(query.unwrap(), "weather temperature=82i 11");
    }

    #[test]
    fn test_write_builder_only_tags() {
        let query = Timestamp::Hours(11)
            .into_query("weather".to_string())
            .add_tag("season", "summer")
            .build();

        assert!(query.is_err(), "Query missing one or more fields");
    }

    #[test]
    fn test_write_builder_full_query() {
        let query = Timestamp::Hours(11)
            .into_query("weather".to_string())
            .add_field("temperature", 82)
            .add_tag("location", "us-midwest")
            .add_tag("season", "summer")
            .build();

        assert!(query.is_ok(), "Query was empty");
        assert_eq!(
            query.unwrap(),
            r#"weather,location=us-midwest,season=summer temperature=82i 11"#
        );
    }

    #[test]
    fn test_correct_query_type() {
        use crate::query::QueryType;

        let query = Timestamp::Hours(11)
            .into_query("weather".to_string())
            .add_field("temperature", 82)
            .add_tag("location", "us-midwest")
            .add_tag("season", "summer");

        assert_eq!(query.get_type(), QueryType::WriteQuery("h".to_owned()));
    }

    #[test]
    fn test_escaping() {
        let query = Timestamp::Hours(11)
            .into_query("wea, ther=")
            .add_field("temperature", 82)
            .add_field("\"temp=era,t ure\"", r#"too"\\hot"#)
            .add_field("float", 82.0)
            .add_tag("location", "us-midwest")
            .add_tag("loc, =\"ation", r#"us, "mid=west"#)
            .build();

        assert!(query.is_ok(), "Query was empty");
        let query_res = query.unwrap().get();
        assert_eq!(
            query_res,
            r#"wea\,\ ther=,location=us-midwest,loc\,\ \="ation=us\,\ \"mid\=west temperature=82i,"temp\=era\,t\ ure"="too\"\\\\hot",float=82 11"#
        );
    }

    #[test]
    fn test_batch() {
        let q0 = Timestamp::Hours(11)
            .into_query("weather")
            .add_field("temperature", 82)
            .add_tag("location", "us-midwest");

        let q1 = Timestamp::Hours(12)
            .into_query("weather")
            .add_field("temperature", 65)
            .add_tag("location", "us-midwest");

        let query = vec![q0, q1].build();

        assert_eq!(
            query.unwrap().get(),
            r#"weather,location=us-midwest temperature=82i 11
weather,location=us-midwest temperature=65i 12"#
        );
    }
}