Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
from dataclasses import dataclass, field
from itertools import repeat
from typing import List, Union
@dataclass
class Query:
select_: str
from_: str
where_: str
group_by: List[str] = field(default_factory=list)
def __str__(self):
ret = f'SELECT \"{self.select_}\" '
ret += f'FROM \"{self.from_}\" '
ret += f'WHERE ({self.where_}) AND $timeFilter '
group_by = ', '.join(f'"{tag}"' for tag in self.group_by)
ret += f'GROUP BY {group_by}'
return ret
def show_tag_values(table: str, key_name: str) -> str:
"""Return influx query to get all tag values from a measurment."""
return f"SHOW TAG VALUES FROM \"{table}\" WITH key = \"{key_name}\""
def get_variable_condition(variable_name: str) -> str:
clean = variable_name.strip()
if not clean:
raise ValueError("Empty variable name")
return f'"{clean}" =~ /^${clean}$/'
def join_conditions(conditions: List[str], operators: Union[List[str], str]):
ops = operators
if isinstance(operators, str):
ops = repeat(operators, len(conditions) - 1)
elif len(operators) == 1:
ops = repeat(operators[0], len(conditions) - 1)
else:
if len(conditions) - 1 != len(operators):
raise ValueError("unfitting lengths of conditions and operators")
ret = conditions[0]
for op, cond in zip(ops, conditions[1:]):
ret += f' {op} {cond}'
return ret
def join_variable_and(variable_names: List[str]) -> str:
return join_conditions(
[get_variable_condition(name) for name in variable_names],
"AND"
)