1- from flask import Flask , request
2- import chdb
31import os
2+ import select
3+
4+ import chdb
5+ from flask import Flask , request
46
57app = Flask (__name__ , static_folder = "public" , static_url_path = "" )
68
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+
736@app .route ('/' , methods = ["GET" ])
837def clickhouse ():
938 query = request .args .get ('query' , default = "" , type = str )
1039 format = request .args .get ('default_format' , default = "CSV" , type = str )
1140 if not query :
1241 return app .send_static_file ('play.html' )
1342
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+
1649
1750@app .route ('/' , methods = ["POST" ])
1851def play ():
@@ -21,13 +54,18 @@ def play():
2154 if not query :
2255 return app .send_static_file ('play.html' )
2356
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+
2663
2764@app .errorhandler (404 )
2865def handle_404 (e ):
2966 return app .send_static_file ('play.html' )
3067
68+
3169host = os .getenv ('HOST' , '0.0.0.0' )
3270port = os .getenv ('PORT' , 8123 )
3371app .run (host = host , port = port )
0 commit comments