From 01f01eaa598bf7311e4474d67b221ca8950449fe Mon Sep 17 00:00:00 2001 From: Rubhan Azeem Date: Mon, 13 Nov 2023 16:13:29 +0100 Subject: [PATCH] fix: escape timestamps in fields and tags values --- lib/influxdb2/client/point.rb | 24 +++++++++++++----------- test/influxdb/point_test.rb | 5 ++++- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/lib/influxdb2/client/point.rb b/lib/influxdb2/client/point.rb index 368779cb..316631b3 100644 --- a/lib/influxdb2/client/point.rb +++ b/lib/influxdb2/client/point.rb @@ -127,7 +127,7 @@ def to_line_protocol return nil if fields.empty? line_protocol << " #{fields}" if fields - timestamp = _escape_time + timestamp = _escape_time(@time) line_protocol << " #{timestamp}" if timestamp line_protocol @@ -185,6 +185,8 @@ def _escape_value(value) '"'.freeze + result + '"'.freeze elsif value.is_a?(Integer) "#{value}i" + elsif value.is_a?(Time) + "#{_escape_time(value)}i" elsif [Float::INFINITY, -Float::INFINITY].include?(value) '' else @@ -192,16 +194,16 @@ def _escape_value(value) end end - def _escape_time - if @time.nil? + def _escape_time(value) + if value.nil? nil - elsif @time.is_a?(Integer) - @time.to_s - elsif @time.is_a?(Float) - @time.round.to_s - elsif @time.is_a?(Time) - nano_seconds = @time.to_i * 1e9 - nano_seconds += @time.tv_nsec + elsif value.is_a?(Integer) + value.to_s + elsif value.is_a?(Float) + value.round.to_s + elsif value.is_a?(Time) + nano_seconds = value.to_i * 1e9 + nano_seconds += value.tv_nsec case @precision || DEFAULT_WRITE_PRECISION when InfluxDB2::WritePrecision::MILLISECOND then (nano_seconds / 1e6).round @@ -213,7 +215,7 @@ def _escape_time nano_seconds.round end else - @time.to_s + value.to_s end end end diff --git a/test/influxdb/point_test.rb b/test/influxdb/point_test.rb index d0d9c213..bb8ee771 100644 --- a/test/influxdb/point_test.rb +++ b/test/influxdb/point_test.rb @@ -64,6 +64,7 @@ def test_override_tag_and_field end def test_field_types + time = Time.utc(2023, 11, 1) point = InfluxDB2::Point.new(name: 'h2o') .add_tag('tag_b', 'b') .add_tag('tag_a', 'a') @@ -73,8 +74,10 @@ def test_field_types .add_field('n4', 5.5) .add_field('bool', true) .add_field('string', 'string value') + .add_field('started', time) - expected = 'h2o,tag_a=a,tag_b=b bool=true,n1=-2i,n2=10i,n3=1265437718438866624512i,n4=5.5,string="string value"' + expected = 'h2o,tag_a=a,tag_b=b bool=true,n1=-2i,n2=10i,n3=1265437718438866624512i,n4=5.5,string="string value", + started=1698796800000000000' assert_equal expected, point.to_line_protocol end