Skip to content

Commit 03b77e1

Browse files
authored
Merge pull request #3 from jbuckmccready/fix_escaping_inputs
Properly escape strings and symbols for ILP format
2 parents 4f8763e + ee89558 commit 03b77e1

File tree

1 file changed

+34
-2
lines changed

1 file changed

+34
-2
lines changed

types.go

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"encoding/base64"
55
"encoding/json"
66
"fmt"
7+
"strings"
78
"time"
89
)
910

@@ -88,12 +89,12 @@ func serializeValue(v interface{}, qdbType QuestDBType) (string, error) {
8889
case Symbol:
8990
switch val := v.(type) {
9091
case string:
91-
return val, nil
92+
return quoteEscape(val, needsEscapeForSymbol, quoteSymbolFn), nil
9293
}
9394
case String:
9495
switch val := v.(type) {
9596
case string:
96-
return fmt.Sprintf("\"%s\"", val), nil
97+
return quoteEscape(val, needsEscapeForStr, quoteStringFn), nil
9798
}
9899
case Long:
99100
switch val := v.(type) {
@@ -147,6 +148,37 @@ func serializeValue(v interface{}, qdbType QuestDBType) (string, error) {
147148
return "", fmt.Errorf("type %T is not compatible with %s", v, qdbType)
148149
}
149150

151+
// Quote and escape an ILP input value, returns new string that is properly quoted and escaped.
152+
func quoteEscape(s string, needsEscape func(byte) bool, quoteFn func(*strings.Builder)) string {
153+
var b strings.Builder
154+
quoteFn(&b)
155+
for i := 0; i < len(s); i++ {
156+
if needsEscape(s[i]) {
157+
b.WriteByte('\\')
158+
}
159+
b.WriteByte(s[i])
160+
}
161+
quoteFn(&b)
162+
163+
return b.String()
164+
}
165+
166+
func needsEscapeForStr(c byte) bool {
167+
return c == '\n' || c == '\r' || c == '\\' || c == '"'
168+
}
169+
170+
func quoteStringFn(b *strings.Builder) {
171+
b.WriteByte('"')
172+
}
173+
174+
func needsEscapeForSymbol(c byte) bool {
175+
return c == '\n' || c == '\r' || c == '\\' || c == ' ' || c == ',' || c == '='
176+
}
177+
178+
func quoteSymbolFn(*strings.Builder) {
179+
// no op, symbols are not quoted in ILP format
180+
}
181+
150182
var supportedQDBTypes = []QuestDBType{
151183
Boolean,
152184
Byte,

0 commit comments

Comments
 (0)