Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix backslash handling in rows_from_chunks #249

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions pydruid/db/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,20 +394,27 @@ def rows_from_chunks(chunks):
body = "".join((body, chunk))

# find last complete row
# see also: https://www.json.org/
boundary = 0
brackets = 0
in_string = False
in_escape = False
for i, char in enumerate(body):
if char == '"':
if not in_string:
in_string = True
elif body[i - 1] != "\\":
in_string = False

if in_string:
if in_escape:
# we're just looking for string boundaries, so we can
# ignore the trailing X in escapes like \uXXXX, since each
# of those X characters must be alphanumeric anyway
in_escape = False
elif char == "\\":
in_escape = True
elif char == '"':
in_string = False
continue

if char == "{":
if char == '"':
in_string = True
elif char == "{":
brackets += 1
elif char == "}":
brackets -= 1
Expand Down
12 changes: 12 additions & 0 deletions tests/db/test_rows_from_chunks.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,18 @@ def test_rows_from_chunks_quote_in_string(self):
result = list(rows_from_chunks(chunks))
self.assertEqual(result, expected)

def test_rows_from_chunks_string_ending_with_backslash(self):
chunks = [r'[{"name": "\\"}]']
expected = [{"name": "\\"}]
result = list(rows_from_chunks(chunks))
self.assertEqual(result, expected)

def test_rows_from_chunks_multiple_rows_ending_with_backslashes(self):
chunks = [r'[{"name": "alice"}, {"name": "bob\\"}, {"name": "charlie\\"}]']
expected = [{"name": "alice"}, {"name": "bob\\"}, {"name": "charlie\\"}]
result = list(rows_from_chunks(chunks))
self.assertEqual(result, expected)


if __name__ == "__main__":
unittest.main()