Skip to content

Commit

Permalink
Support multi column results with using mongo query runner (getredash…
Browse files Browse the repository at this point in the history
…#6558)

* Support multi column results with using mongo query runner

* format

Signed-off-by: del-zhenwu <[email protected]>

* Update test_mongodb.py

update unit test case: nested dict for mongodb runner

* Update test_mongodb.py

* fix formatting

---------

Signed-off-by: del-zhenwu <[email protected]>
Co-authored-by: del-zhenwu <[email protected]>
Co-authored-by: del-zhenwu <[email protected]>
  • Loading branch information
3 people authored and harveyrendell committed Jan 8, 2025
1 parent 7d8b752 commit 5d8ccbb
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 27 deletions.
47 changes: 21 additions & 26 deletions redash/query_runner/mongodb.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,39 +93,34 @@ def _get_column_by_name(columns, column_name):
return None


def _parse_dict(dic):
res = {}
for key, value in dic.items():
if isinstance(value, dict):
for tmp_key, tmp_value in _parse_dict(value).items():
new_key = "{}.{}".format(key, tmp_key)
res[new_key] = tmp_value
else:
res[key] = value
return res


def parse_results(results):
rows = []
columns = []

for row in results:
parsed_row = {}

for key in row:
if isinstance(row[key], dict):
for inner_key in row[key]:
column_name = "{}.{}".format(key, inner_key)
if _get_column_by_name(columns, column_name) is None:
columns.append(
{
"name": column_name,
"friendly_name": column_name,
"type": TYPES_MAP.get(type(row[key][inner_key]), TYPE_STRING),
}
)

parsed_row[column_name] = row[key][inner_key]

else:
if _get_column_by_name(columns, key) is None:
columns.append(
{
"name": key,
"friendly_name": key,
"type": TYPES_MAP.get(type(row[key]), TYPE_STRING),
}
)

parsed_row[key] = row[key]
parsed_row = _parse_dict(row)
for column_name, value in parsed_row.items():
columns.append(
{
"name": column_name,
"friendly_name": column_name,
"type": TYPES_MAP.get(type(value), TYPE_STRING),
}
)

rows.append(parsed_row)

Expand Down
3 changes: 2 additions & 1 deletion tests/query_runner/test_mongodb.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def test_parses_nested_results(self):
"column": 2,
"column2": "test",
"column3": "hello",
"nested": {"a": 2, "b": "str2", "c": "c"},
"nested": {"a": 2, "b": "str2", "c": "c", "d": {"e": 3}},
},
]

Expand All @@ -157,6 +157,7 @@ def test_parses_nested_results(self):
"nested.a": 2,
"nested.b": "str2",
"nested.c": "c",
"nested.d.e": 3,
},
)

Expand Down

0 comments on commit 5d8ccbb

Please sign in to comment.