Skip to content

Commit 027a82d

Browse files
author
boonhapus
committed
🐛 implement proper data response
1 parent 05eb4cf commit 027a82d

File tree

2 files changed

+97
-26
lines changed

2 files changed

+97
-26
lines changed

cs_tools/api/middlewares/tql.py

Lines changed: 48 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,15 @@
1717
])
1818

1919

20+
def _to_table(headers, rows=None):
21+
if rows is None:
22+
rows = []
23+
24+
header = [column['name'] for column in headers]
25+
data = [dict(zip(header, row['v'])) for row in rows]
26+
return data
27+
28+
2029
class TQLMiddleware:
2130
"""
2231
"""
@@ -73,25 +82,36 @@ def query(
7382
}
7483

7584
r = self.ts.api.ts_dataservice.query(data, timeout=http_timeout)
76-
d = [json.loads(_) for _ in r.iter_lines() if _]
77-
print(d)
78-
raise
79-
return d['result']['message']
85+
i = [json.loads(_) for _ in r.iter_lines() if _]
86+
87+
out = []
88+
89+
for row in i:
90+
if 'table' in row['result']:
91+
out.append({'data': _to_table(**row['result']['table'])})
92+
93+
if 'message' in row['result']:
94+
out.append({'messages': row['result']['message']})
95+
96+
return out
8097

8198
@validate_arguments
8299
def command(
83100
self,
84101
command: str,
85102
*,
86103
database: str = None,
87-
schema_: Annotated[str, Field(alias='schema')] = 'falcon_default_schema',
104+
schema_: str = 'falcon_default_schema',
88105
raise_errors: bool = False,
89106
http_timeout: int = 5.0
90107
) -> List[Dict[str, Any]]:
91108
"""
92109
"""
93110
self._check_privileges()
94111

112+
if not command.strip().endswith(';'):
113+
command = f'{command.strip()};'
114+
95115
data = {
96116
'context': {
97117
'database': database,
@@ -104,11 +124,18 @@ def command(
104124
}
105125

106126
r = self.ts.api.ts_dataservice.query(data, timeout=http_timeout)
127+
i = [json.loads(_) for _ in r.iter_lines() if _]
128+
129+
out = []
130+
131+
for row in i:
132+
if 'table' in row['result']:
133+
out.append({'data': _to_table(**row['result']['table'])})
134+
135+
if 'message' in row['result']:
136+
out.append({'messages': row['result']['message']})
107137

108-
d = [json.loads(_) for _ in r.iter_lines() if _]
109-
d = r.json()
110-
log.debug(d)
111-
return d['result']['message']
138+
return out
112139

113140
@validate_arguments
114141
def script(
@@ -133,18 +160,15 @@ def script(
133160
}
134161

135162
r = self.ts.api.ts_dataservice.script(data, timeout=http_timeout)
136-
d = [json.loads(_) for _ in r.iter_lines() if _]
137-
138-
for _ in d:
139-
if 'message' in _['result']:
140-
m = self.ts.api.ts_dataservice._parse_api_messages(_['result']['message'])
141-
if 'table' in _['result']:
142-
m = self.ts.api.ts_dataservice._parse_tql_query(_['result']['table'])
143-
144-
log.debug(m)
145-
146-
if raise_errors and 'returned error' in m:
147-
if 'create table' in m.lower():
148-
raise TableAlreadyExists()
149-
else:
150-
raise ValueError(m)
163+
i = [json.loads(_) for _ in r.iter_lines() if _]
164+
165+
out = []
166+
167+
for row in i:
168+
if 'table' in row['result']:
169+
out.append({'data': _to_table(**row['result']['table'])})
170+
171+
if 'message' in row['result']:
172+
out.append({'messages': row['result']['message']})
173+
174+
return out

cs_tools/cli/tools/rtql/app.py

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from typer import Argument as A_, Option as O_
55
import typer
6+
import rich
67

78
from cs_tools.cli.dependency import depends
89
from cs_tools.cli.options import CONFIG_OPT, VERBOSE_OPT, TEMP_DIR_OPT
@@ -78,7 +79,30 @@ def file(
7879
cat create-schema.sql | tql
7980
"""
8081
ts = ctx.obj.thoughtspot
81-
ts.tql.script(file)
82+
r = ts.tql.script(file)
83+
84+
color_map = {
85+
'INFO': '[white]',
86+
'ERROR': '[red]'
87+
}
88+
89+
for response in r:
90+
if 'messages' in response:
91+
for message in response['messages']:
92+
c = color_map.get(message['type'], '[yellow]')
93+
m = message['value']
94+
95+
if m.strip() == 'Statement executed successfully.':
96+
c = '[bold green]'
97+
if m.strip().endswith(';'):
98+
c = '[cyan]'
99+
100+
console.print(c + m, end='')
101+
102+
if 'data' in response:
103+
t = rich.table.Table(*response['data'][0].keys(), box=rich.box.HORIZONTALS)
104+
[t.add_row(*_.values()) for _ in response['data']]
105+
console.print('\n', t)
82106

83107

84108
@app.command(cls=CSToolsCommand)
@@ -116,4 +140,27 @@ def command(
116140
console.print('[red]no valid input given to rtql command')
117141
raise typer.Exit()
118142

119-
ts.tql.command(command, schema=schema)
143+
r = ts.tql.command(command, schema_=schema)
144+
145+
color_map = {
146+
'INFO': '[white]',
147+
'ERROR': '[red]'
148+
}
149+
150+
for response in r:
151+
if 'messages' in response:
152+
for message in response['messages']:
153+
c = color_map.get(message['type'], '[yellow]')
154+
m = message['value']
155+
156+
if m.strip() == 'Statement executed successfully.':
157+
c = '[bold green]'
158+
if m.strip().endswith(';'):
159+
c = '[cyan]'
160+
161+
console.print(c + m, end='')
162+
163+
if 'data' in response:
164+
t = rich.table.Table(*response['data'][0].keys(), box=rich.box.HORIZONTALS)
165+
[t.add_row(*_.values()) for _ in response['data']]
166+
console.print('\n', t)

0 commit comments

Comments
 (0)