@@ -8,6 +8,25 @@ use std::fmt::{Display, Formatter};
8
8
9
9
// todo: batch write queries
10
10
11
+ pub trait WriteField {
12
+ fn add_to_fields ( self , tag : String , fields : & mut Vec < ( String , String ) > ) ;
13
+ }
14
+
15
+ impl < T : Into < Type > > WriteField for T {
16
+ fn add_to_fields ( self , tag : String , fields : & mut Vec < ( String , String ) > ) {
17
+ let val: Type = self . into ( ) ;
18
+ fields. push ( ( tag, val. to_string ( ) ) ) ;
19
+ }
20
+ }
21
+
22
+ impl < T : Into < Type > > WriteField for Option < T > {
23
+ fn add_to_fields ( self , tag : String , fields : & mut Vec < ( String , String ) > ) {
24
+ if let Some ( val) = self {
25
+ val. add_to_fields ( tag, fields) ;
26
+ }
27
+ }
28
+ }
29
+
11
30
/// Internal Representation of a Write query that has not yet been built
12
31
pub struct WriteQuery {
13
32
fields : Vec < ( String , String ) > ,
@@ -39,13 +58,12 @@ impl WriteQuery {
39
58
///
40
59
/// Query::write_query(Timestamp::NOW, "measurement").add_field("field1", 5).build();
41
60
/// ```
42
- pub fn add_field < S , I > ( mut self , tag : S , value : I ) -> Self
61
+ pub fn add_field < S , F > ( mut self , tag : S , value : F ) -> Self
43
62
where
44
63
S : Into < String > ,
45
- I : Into < Type > ,
64
+ F : WriteField ,
46
65
{
47
- let val: Type = value. into ( ) ;
48
- self . fields . push ( ( tag. into ( ) , val. to_string ( ) ) ) ;
66
+ value. add_to_fields ( tag. into ( ) , & mut self . fields ) ;
49
67
self
50
68
}
51
69
@@ -206,6 +224,17 @@ mod tests {
206
224
) ;
207
225
}
208
226
227
+ #[ test]
228
+ fn test_write_builder_optional_fields ( ) {
229
+ let query = Query :: write_query ( Timestamp :: HOURS ( 11 ) , "weather" )
230
+ . add_field ( "temperature" , Some ( 82u64 ) )
231
+ . add_field ( "wind_strength" , <Option < u64 > >:: None )
232
+ . build ( ) ;
233
+
234
+ assert ! ( query. is_ok( ) , "Query was empty" ) ;
235
+ assert_eq ! ( query. unwrap( ) , "weather temperature=82 11" ) ;
236
+ }
237
+
209
238
#[ test]
210
239
fn test_write_builder_only_tags ( ) {
211
240
let query = Query :: write_query ( Timestamp :: HOURS ( 11 ) , "weather" )
0 commit comments