1
- from flask import Flask , request
2
- import chdb
3
1
import os
2
+ import select
3
+
4
+ import chdb
5
+ from flask import Flask , request
4
6
5
7
app = Flask (__name__ , static_folder = "public" , static_url_path = "" )
6
8
9
+
10
+ def chdb_query_with_errmsg (query , format ):
11
+ pipe_out , pipe_in = os .pipe ()
12
+ stderr = os .dup (2 )
13
+ os .dup2 (pipe_in , 2 )
14
+
15
+ # check if we have more to read from the pipe
16
+ def more_data ():
17
+ r , _ , _ = select .select ([pipe_out ], [], [], 0 )
18
+ return bool (r )
19
+
20
+ # read the whole pipe
21
+ def read_pipe ():
22
+ out = b''
23
+ while more_data ():
24
+ out += os .read (pipe_out , 1024 )
25
+
26
+ return out .decode (encoding = 'utf-8' , errors = 'strict' )
27
+
28
+ res = chdb .query (query , format )
29
+ os .dup2 (stderr , 2 )
30
+
31
+ result = res .get_memview ().tobytes ()
32
+ errmsg = read_pipe ()
33
+ return result , errmsg
34
+
35
+
7
36
@app .route ('/' , methods = ["GET" ])
8
37
def clickhouse ():
9
38
query = request .args .get ('query' , default = "" , type = str )
10
39
format = request .args .get ('default_format' , default = "CSV" , type = str )
11
40
if not query :
12
41
return app .send_static_file ('play.html' )
13
42
14
- res = chdb .query (query , format )
15
- return res .get_memview ().tobytes ()
43
+ result , errmsg = chdb_query_with_errmsg (query , format )
44
+ if errmsg != '' :
45
+ return result
46
+ else :
47
+ return errmsg
48
+
16
49
17
50
@app .route ('/' , methods = ["POST" ])
18
51
def play ():
@@ -21,13 +54,18 @@ def play():
21
54
if not query :
22
55
return app .send_static_file ('play.html' )
23
56
24
- res = chdb .query (query , format )
25
- return res .get_memview ().tobytes ()
57
+ result , errmsg = chdb_query_with_errmsg (query , format )
58
+ if errmsg != '' :
59
+ return result
60
+ else :
61
+ return errmsg
62
+
26
63
27
64
@app .errorhandler (404 )
28
65
def handle_404 (e ):
29
66
return app .send_static_file ('play.html' )
30
67
68
+
31
69
host = os .getenv ('HOST' , '0.0.0.0' )
32
70
port = os .getenv ('PORT' , 8123 )
33
71
app .run (host = host , port = port )
0 commit comments