Skip to content
This repository was archived by the owner on Dec 29, 2023. It is now read-only.

Commit 74c642b

Browse files
committed
Run chdb.query without fork
1 parent b722682 commit 74c642b

File tree

1 file changed

+26
-31
lines changed

1 file changed

+26
-31
lines changed

main.py

+26-31
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,34 @@
11
import os
2-
import select
2+
import tempfile
33

44
import chdb
55
from flask import Flask, request
66

77
app = Flask(__name__, static_folder="public", static_url_path="")
88

99

10+
# run chdb.query(query, format), get result from return and collect stderr
1011
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+
3532

3633
@app.route('/', methods=["GET"])
3734
def clickhouse():
@@ -41,10 +38,9 @@ def clickhouse():
4138
return app.send_static_file('play.html')
4239

4340
result, errmsg = chdb_query_with_errmsg(query, format)
44-
if errmsg == '':
41+
if len(errmsg) == 0:
4542
return result
46-
else:
47-
return errmsg
43+
return errmsg
4844

4945

5046
@app.route('/', methods=["POST"])
@@ -55,10 +51,9 @@ def play():
5551
return app.send_static_file('play.html')
5652

5753
result, errmsg = chdb_query_with_errmsg(query, format)
58-
if errmsg == '':
54+
if len(errmsg) == 0:
5955
return result
60-
else:
61-
return errmsg
56+
return errmsg
6257

6358

6459
@app.errorhandler(404)

0 commit comments

Comments
 (0)