1
1
import os
2
- import select
2
+ import tempfile
3
3
4
4
import chdb
5
5
from flask import Flask , request
6
6
7
7
app = Flask (__name__ , static_folder = "public" , static_url_path = "" )
8
8
9
9
10
+ # run chdb.query(query, format), get result from return and collect stderr
10
11
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
-
12
+ # Redirect stdout and stderr to the buffers
13
+ try :
14
+ new_stderr = tempfile .TemporaryFile ()
15
+ old_stderr_fd = os .dup (2 )
16
+ os .dup2 (new_stderr .fileno (), 2 )
17
+ # Call the function
18
+ output = chdb .query (query , format ).bytes ()
19
+
20
+ new_stderr .flush ()
21
+ new_stderr .seek (0 )
22
+ errmsg = new_stderr .read ()
23
+
24
+ # cleanup and recover
25
+ new_stderr .close ()
26
+ os .dup2 (old_stderr_fd , 2 )
27
+ except Exception as e :
28
+ # An error occurred, print it to stderr
29
+ print (f"An error occurred: { e } " )
30
+ return output , errmsg
31
+
35
32
36
33
@app .route ('/' , methods = ["GET" ])
37
34
def clickhouse ():
@@ -41,10 +38,9 @@ def clickhouse():
41
38
return app .send_static_file ('play.html' )
42
39
43
40
result , errmsg = chdb_query_with_errmsg (query , format )
44
- if errmsg == '' :
41
+ if len ( errmsg ) == 0 :
45
42
return result
46
- else :
47
- return errmsg
43
+ return errmsg
48
44
49
45
50
46
@app .route ('/' , methods = ["POST" ])
@@ -55,10 +51,9 @@ def play():
55
51
return app .send_static_file ('play.html' )
56
52
57
53
result , errmsg = chdb_query_with_errmsg (query , format )
58
- if errmsg == '' :
54
+ if len ( errmsg ) == 0 :
59
55
return result
60
- else :
61
- return errmsg
56
+ return errmsg
62
57
63
58
64
59
@app .errorhandler (404 )
0 commit comments