Skip to content

Commit

Permalink
fix: escape timestamps in fields and tags values
Browse files Browse the repository at this point in the history
  • Loading branch information
rubhanazeem committed Nov 13, 2023
1 parent d0fb0d5 commit 01f01ea
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 12 deletions.
24 changes: 13 additions & 11 deletions lib/influxdb2/client/point.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -185,23 +185,25 @@ 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
value.to_s
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
Expand All @@ -213,7 +215,7 @@ def _escape_time
nano_seconds.round
end
else
@time.to_s
value.to_s
end
end
end
Expand Down
5 changes: 4 additions & 1 deletion test/influxdb/point_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand All @@ -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

Expand Down

0 comments on commit 01f01ea

Please sign in to comment.