@@ -8,6 +8,25 @@ use std::fmt::{Display, Formatter};
88
99// todo: batch write queries
1010
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+
1130/// Internal Representation of a Write query that has not yet been built
1231pub struct WriteQuery {
1332 fields : Vec < ( String , String ) > ,
@@ -39,13 +58,12 @@ impl WriteQuery {
3958 ///
4059 /// Query::write_query(Timestamp::NOW, "measurement").add_field("field1", 5).build();
4160 /// ```
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
4362 where
4463 S : Into < String > ,
45- I : Into < Type > ,
64+ F : WriteField ,
4665 {
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 ) ;
4967 self
5068 }
5169
@@ -206,6 +224,17 @@ mod tests {
206224 ) ;
207225 }
208226
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+
209238 #[ test]
210239 fn test_write_builder_only_tags ( ) {
211240 let query = Query :: write_query ( Timestamp :: HOURS ( 11 ) , "weather" )
0 commit comments