简体   繁体   English

字符串末尾的反斜杠在插入InfluxDB时导致错误

[英]backslash at end of string causes error when inserting into InfluxDB

I have a string: 我有一个字符串:

string = "\\"
puts string
# => \

I am interpolating this into a new string and sending to a database. 我将其插值到新字符串中并发送到数据库。 However the database (InfluxDB) uses backslashes as escape characters so pushing this string can cause an error. 但是,数据库(InfluxDB)使用反斜杠作为转义字符,因此推送此字符串可能会导致错误。

For example, if I pass the following to Influx it will cause an "unterminated string" error: 例如,如果我将以下内容传递给Influx,将导致“未终止的字符串”错误:

insert_cmd = <<-TXT
  INSERT INTO my_db.default.my_measurement,my_tag=1 my_val="#{string}"
TXT

My question is how can I replace \\ in a string with \\\\ (two actual backslashes). 我的问题是我怎么能替换\\与字符串\\\\ (两个实际的反斜杠)。

I have it working with gsub("\\\\", "\\\\\\\\\\\\") but I don't understand why this works and the following doesn't: 我有它与gsub("\\\\", "\\\\\\\\\\\\")但我不明白为什么这样行,而以下行不行:

string.gsub("\\", "\\\\")
# SyntaxError: (irb):10: syntax error, unexpected $undefined, expecting end-of-input

Why doesn't this work? 为什么不起作用? Why does gsub("\\\\", "\\\\\\\\\\\\") work? 为什么gsub("\\\\", "\\\\\\\\\\\\")起作用? Is there a better way? 有没有更好的办法?


solved 解决了

As I mentioned in a comment, actually I am not manually interpolating into a INSERT INTO string. 正如我在评论中提到的那样,实际上我不是在手动插入INSERT INTO字符串。 I am using influxdb-ruby: 我正在使用influxdb-ruby:

INFLUXDB_CLIENT.write_point("things", time: Time.now.to_i, values: { foo: "\\" })

It turns out this is a bug with that gem: https://github.com/influxdata/influxdb-ruby/issues/200 事实证明,这是该宝石的错误: https : //github.com/influxdata/influxdb-ruby/issues/200

It is fixed in v 0.4.2 and i was using 0.4.1 在v 0.4.2中已修复,而我在使用0.4.1

You just use parameterized query strings: 您只需使用参数化查询字符串:

INSERT INTO my_db.default.my_measurement,my_tag=1 my_val=%{1}

Where when you call it you do this: 调用它的位置:

influxdb.query("...query...", params: [ string ])

What you did was create a classic injection bug by sending unescaped data into a query. 您所做的是通过将未转义的数据发送到查询中来创建经典的注入错误 The same principle applies in any database with a plain-text string representation, or even other data formats like HTML and JavaScript. 相同的原则适用于任何具有纯文本字符串表示形式的数据库,甚至适用于HTML和JavaScript等其他数据格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM