1+ from clickhouse_connect .driver .client import Client
2+ from string import Formatter
3+ from typing import List , Union
4+ import sys
5+
6+
7+ class MooseClient :
8+ def __init__ (self , ch_client : Client ):
9+ self .ch_client = ch_client
10+
11+ def query (self , input , variables ):
12+ params = {}
13+ values = {}
14+
15+ for i , (_ , variable_name , _ , _ ) in enumerate (Formatter ().parse (input )):
16+ if variable_name :
17+ value = variables [variable_name ]
18+ if isinstance (value , list ) and len (value ) == 1 :
19+ # handling passing the value of the query string dict directly to variables
20+ value = value [0 ]
21+
22+ t = 'String' if isinstance (value , str ) else \
23+ 'Int64' if isinstance (value , int ) else \
24+ 'Float64' if isinstance (value , float ) else "String" # unknown type
25+
26+ params [variable_name ] = f'{{p{ i } : { t } }}'
27+ values [f'p{ i } ' ] = value
28+ clickhouse_query = input .format_map (params )
29+
30+ val = self .ch_client .query (clickhouse_query , values )
31+
32+ return list (val .named_results ())
33+
34+
35+ class Sql :
36+ def __init__ (self , raw_strings : List [str ], raw_values : List ['RawValue' ]):
37+ if len (raw_strings ) - 1 != len (raw_values ):
38+ if len (raw_strings ) == 0 :
39+ raise TypeError ("Expected at least 1 string" )
40+ raise TypeError (f"Expected { len (raw_strings )} strings to have { len (raw_strings ) - 1 } values" )
41+
42+ values_length = sum (1 if not isinstance (value , Sql ) else len (value .values ) for value in raw_values )
43+
44+ self .values : List ['Value' ] = [None ] * values_length
45+ self .strings : List [str ] = [None ] * (values_length + 1 )
46+
47+ self .strings [0 ] = raw_strings [0 ]
48+
49+ i = 0
50+ pos = 0
51+ while i < len (raw_values ):
52+ child = raw_values [i ]
53+ raw_string = raw_strings [i + 1 ]
54+
55+ if isinstance (child , Sql ):
56+ self .strings [pos ] += child .strings [0 ]
57+
58+ for child_index in range (len (child .values )):
59+ self .values [pos ] = child .values [child_index ]
60+ pos += 1
61+ self .strings [pos ] = child .strings [child_index + 1 ]
62+
63+ self .strings [pos ] += raw_string
64+ else :
65+ self .values [pos ] = child
66+ pos += 1
67+ self .strings [pos ] = raw_string
68+
69+ i += 1
70+
71+ def sigterm_handler ():
72+ print ("SIGTERM received" )
73+ sys .exit (0 )
74+
175def stub ():
276 print ("Hello from moose-lib!" )
0 commit comments