Repository navigation
Expand file tree
/
Copy pathLocalChdb.cpp
More file actions
1193 lines (1052 loc) · 41.1 KB
/
Copy pathLocalChdb.cpp
File metadata and controls
1193 lines (1052 loc) · 41.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "LocalChdb.h"
#include "PyBorrowGuard.h"
#include <base/scope_guard.h>
#include "chdb-internal.h"
#include "DataFrameQueryResult.h"
#include "PandasDataFrameBuilder.h"
#include "PythonArrowStream.h"
#include "PythonImporter.h"
#include "ChdbPyType.h"
#include "ChdbGlobalFunctions.h"
#include "PythonUDFRegistry.h"
#include "StoragePython.h"
#include "ChdbClient.h"
#include "PyDateTimeHelper.h"
#include "chdb.h"
#ifndef CHDB_FREE_THREADING
#include <pybind11/detail/non_limited_api.h>
#endif
#include <pybind11/pybind11.h>
#include <IO/Progress.h>
#include <Poco/String.h>
#include <Common/logger_useful.h>
#include <sstream>
#include <stdexcept>
#if USE_JEMALLOC
# include <Common/memory.h>
#endif
#if USE_EMBEDDED_COMPILER
# include <Interpreters/JIT/CompiledExpressionCache.h>
#endif
#if USE_CLIENT_AI
# include "AIQueryProcessor.h"
#endif
namespace py = pybind11;
extern bool inside_main = true;
namespace
{
std::string paramValueToString(const py::handle & value)
{
if (value.is_none())
return "NULL";
if (py::isinstance<py::bool_>(value))
return py::cast<bool>(value) ? "1" : "0";
if (py::isinstance<py::list>(value) || py::isinstance<py::tuple>(value))
{
std::vector<std::string> parts;
parts.reserve(static_cast<size_t>(py::len(value)));
for (const auto & item : value)
parts.emplace_back(paramValueToString(item));
std::ostringstream out;
out << '[';
for (size_t i = 0; i < parts.size(); ++i)
{
if (i)
out << ',';
out << parts[i];
}
out << ']';
return out.str();
}
return py::cast<std::string>(py::str(value));
}
DB::NameToNameMap parseParametersDict(const py::dict & params)
{
DB::NameToNameMap parsed;
for (const auto & item : params)
{
const std::string key = py::cast<std::string>(item.first);
const auto & value = item.second;
parsed.emplace(key, paramValueToString(value));
}
return parsed;
}
class QueryParameterGuard
{
public:
QueryParameterGuard(DB::ChdbClient * client_, const DB::NameToNameMap & params) : client(client_)
{
if (client && !params.empty())
{
client->setQueryParameters(params);
applied = true;
}
}
~QueryParameterGuard()
{
if (client && applied)
client->clearQueryParameters();
}
private:
DB::ChdbClient * client;
bool applied = false;
};
DB::ChdbClient * getChdbClient(chdb_connection handle)
{
auto * connection = reinterpret_cast<chdb_conn *>(handle);
if (!checkConnectionValidity(connection))
return nullptr;
return static_cast<DB::ChdbClient *>(connection->server);
}
}
namespace CHDB
{
extern chdb_connection * connect_chdb_with_exception(int argc, char ** argv);
extern void cachePythonTablesFromQuery(chdb_conn * conn, const std::string & query_str);
}
const static char * CURSOR_DEFAULT_FORMAT = "JSONCompactEachRowWithNamesAndTypes";
const static size_t CURSOR_DEFAULT_FORMAT_LEN = strlen(CURSOR_DEFAULT_FORMAT);
chdb_result * queryToBuffer(
const std::string & queryStr,
const std::string & output_format = "CSV",
const std::string & path = {},
const std::string & udfPath = {},
const DB::NameToNameMap & params = {})
{
std::vector<std::string> argv = {"clickhouse", "--multiquery"};
// If format is "Debug" or "debug", then we will add `--verbose` and `--log-level=trace` to argv
if (output_format == "Debug" || output_format == "debug")
{
argv.push_back("--verbose");
argv.push_back("--log-level=test");
// Add format string
argv.push_back("--output-format=CSV");
}
else
{
// Add format string
argv.push_back("--output-format=" + output_format);
}
// If path is not empty, then we will add `--path` to argv. This is used for chdb.Session to support stateful query
if (!path.empty())
{
// Add path string
argv.push_back("--path=" + path);
}
// argv.push_back("--no-system-tables");
// Add query string
argv.push_back("--query=" + queryStr);
// If udfPath is not empty, then we will add `--user_scripts_path` and `--user_defined_executable_functions_config` to argv
// the path should be a one time thing, so the caller should take care of the temporary files deletion
if (!udfPath.empty())
{
argv.push_back("--");
argv.push_back("--user_scripts_path=" + udfPath);
argv.push_back("--user_defined_executable_functions_config=" + udfPath + "/*.xml");
}
for (const auto & [key, value] : params)
{
argv.push_back("--param_" + key + "=" + value);
}
// Convert std::string to char*
std::vector<char *> argv_char;
argv_char.reserve(argv.size());
for (auto & arg : argv)
argv_char.push_back(const_cast<char *>(arg.c_str()));
py::gil_scoped_release release;
return chdb_query_cmdline(argv_char.size(), argv_char.data());
}
// Pybind11 will take over the ownership of the `query_result` object
// using smart ptr will cause early free of the object
query_result * query(
const std::string & queryStr,
const std::string & output_format = "CSV",
const std::string & path = {},
const std::string & udfPath = {},
const py::dict & params = py::dict())
{
return new query_result(queryToBuffer(queryStr, output_format, path, udfPath, parseParametersDict(params)));
}
// The `query_result` and `memoryview_wrapper` will hold `local_result_wrapper` with shared_ptr
memoryview_wrapper * query_result::get_memview()
{
return new memoryview_wrapper(this->result_wrapper);
}
// Parse SQLite-style connection string
std::pair<std::string, std::map<std::string, std::string>> connection_wrapper::parse_connection_string(const std::string & conn_str)
{
std::string path;
std::map<std::string, std::string> params;
if (conn_str.empty() || conn_str == ":memory:")
{
return {":memory:", params};
}
std::string working_str = conn_str;
// Handle file: prefix
if (working_str.starts_with("file:"))
{
working_str = working_str.substr(5);
// Handle triple slash for absolute paths
if (working_str.starts_with("///"))
{
working_str = working_str.substr(2); // Remove two slashes, keep one
}
}
// Split path and parameters
auto query_pos = working_str.find('?');
if (query_pos != std::string::npos)
{
path = working_str.substr(0, query_pos);
std::string params_str = working_str.substr(query_pos + 1);
// Parse parameters
std::istringstream params_stream(params_str);
std::string param;
while (std::getline(params_stream, param, '&'))
{
auto eq_pos = param.find('=');
if (eq_pos != std::string::npos)
{
std::string key = param.substr(0, eq_pos);
std::string value = param.substr(eq_pos + 1);
params[key] = value;
}
else if (!param.empty())
{
// Handle parameters without values
params[param] = "";
}
}
// Handle udf_path
// add user_scripts_path and user_defined_executable_functions_config to params
// these two parameters need "--" as prefix
if (params.contains("udf_path"))
{
std::string udf_path = params["udf_path"];
if (!udf_path.empty())
{
params["--"] = "";
params["user_scripts_path"] = udf_path;
params["user_defined_executable_functions_config"] = udf_path + "/*.xml";
}
// remove udf_path from params
params.erase("udf_path");
}
}
else
{
path = working_str;
}
// Convert relative paths to absolute
if (!path.empty() && path[0] != '/' && path != ":memory:")
{
std::error_code ec;
path = std::filesystem::absolute(path, ec).string();
if (ec)
{
throw std::runtime_error("Failed to resolve path: " + path);
}
}
return {path, params};
}
std::vector<std::string>
connection_wrapper::build_clickhouse_args(const std::string & path, const std::map<std::string, std::string> & params)
{
std::vector<std::string> argv = {"clickhouse"};
if (path != ":memory:")
{
argv.push_back("--path=" + path);
}
// Map SQLite parameters to ClickHouse arguments
for (const auto & [key, value] : params)
{
if (key == "mode")
{
if (value == "ro")
{
is_readonly = true;
/// readonly=2, not 1: writes and DDL are rejected, but the
/// connection may still tune per-query settings (SET /
/// SETTINGS clauses), matching what a SQLite-style mode=ro
/// promises. readonly=1 would reject those too.
argv.push_back("--readonly=2");
}
}
else if (key == "--")
{
// Handle special parameters "--"
argv.push_back("--");
}
else if (value.empty())
{
// Handle parameters without values (like ?withoutarg)
argv.push_back("--" + key);
}
else
{
argv.push_back("--" + key + "=" + value);
}
}
return argv;
}
connection_wrapper::connection_wrapper(const std::string & conn_str)
{
is_readonly = false;
auto [path, params] = parse_connection_string(conn_str);
#if USE_CLIENT_AI
applyAIParams(params);
#endif
auto argv = build_clickhouse_args(path, params);
std::vector<char *> argv_char;
argv_char.reserve(argv.size());
for (auto & arg : argv)
{
argv_char.push_back(const_cast<char *>(arg.c_str()));
}
conn = CHDB::connect_chdb_with_exception(argv_char.size(), argv_char.data());
db_path = path;
is_memory_db = (path == ":memory:");
}
connection_wrapper::~connection_wrapper()
{
py::gil_scoped_release release;
chdb_close_conn(conn);
}
void connection_wrapper::close()
{
if (conn && !progress_callback.is_none())
set_progress_callback(py::none());
{
py::gil_scoped_release release;
chdb_close_conn(conn);
}
// Ensure that if a new connection is created before this object is destroyed that we don't try to close it.
conn = nullptr;
}
void connection_wrapper::set_progress_callback(const py::object & callback)
{
auto * client = getChdbClient(*conn);
if (!client)
return;
if (callback.is_none())
{
progress_callback = py::none();
client->setProgressValuesCallback(nullptr);
return;
}
if (!PyCallable_Check(callback.ptr()))
throw std::runtime_error("progress callback must be callable");
progress_callback = callback;
auto * callback_ptr = callback.ptr();
Py_INCREF(callback_ptr);
auto callback_holder = std::shared_ptr<void>(
callback_ptr,
[](void * ptr)
{
py::gil_scoped_acquire acquire;
Py_DECREF(reinterpret_cast<PyObject *>(ptr));
});
client->setProgressValuesCallback(
[callback_holder](const DB::ProgressValues & values, UInt64 elapsed_ns)
{
py::gil_scoped_acquire acquire;
try
{
py::dict payload;
payload["read_rows"] = py::int_(values.read_rows);
payload["read_bytes"] = py::int_(values.read_bytes);
payload["total_rows_to_read"] = py::int_(values.total_rows_to_read);
payload["total_bytes_to_read"] = py::int_(values.total_bytes_to_read);
payload["elapsed_ns"] = py::int_(elapsed_ns);
payload["written_rows"] = py::int_(values.written_rows);
payload["written_bytes"] = py::int_(values.written_bytes);
payload["result_rows"] = py::int_(values.result_rows);
payload["result_bytes"] = py::int_(values.result_bytes);
py::handle callback_obj(reinterpret_cast<PyObject *>(callback_holder.get()));
callback_obj(payload);
}
catch (const py::error_already_set &)
{
PyErr_Print();
}
});
}
cursor_wrapper * connection_wrapper::cursor()
{
return new cursor_wrapper(this);
}
void connection_wrapper::commit()
{
// do nothing
}
query_result * connection_wrapper::query(const std::string & query_str, const std::string & format, const py::dict & params)
{
if (Poco::toLower(format) == "dataframe")
throw std::runtime_error("Unsupported output format dataframe, please use 'query_df' function");
const auto parsed_params = parseParametersDict(params);
auto * client = getChdbClient(*conn);
QueryParameterGuard guard(client, parsed_params);
CHDB::cachePythonTablesFromQuery(reinterpret_cast<chdb_conn *>(*conn), query_str);
py::gil_scoped_release release;
auto * result = chdb_query_n(*conn, query_str.data(), query_str.size(), format.data(), format.size());
const auto & error_msg = CHDB::chdb_result_error_string(result);
if (!error_msg.empty())
{
std::string msg_copy(error_msg);
chdb_destroy_query_result(result);
throw std::runtime_error(msg_copy);
}
return new query_result(result, false);
}
py::object connection_wrapper::query_df(const std::string & query_str, const py::dict & params)
{
static const std::string format = "dataframe";
chdb_result * result = nullptr;
CHDB::ChunkQueryResult * chunk_result = nullptr;
/// Destroy the result and settle the deferred decrefs on every exit,
/// including exceptions thrown by the pandas conversion (which would
/// otherwise leak the chunks and their borrow guards outright). The GIL
/// is held at scope exit on all paths: the gil_scoped_release block below
/// is destructed before this guard runs.
SCOPE_EXIT({
if (result)
{
chdb_destroy_query_result(result);
CHDB::drainPyBorrowGuardQueue();
}
});
const auto parsed_params = parseParametersDict(params);
auto * client = getChdbClient(*conn);
QueryParameterGuard guard(client, parsed_params);
CHDB::cachePythonTablesFromQuery(reinterpret_cast<chdb_conn *>(*conn), query_str);
{
py::gil_scoped_release release;
result = chdb_query_n(*conn, query_str.data(), query_str.size(), format.data(), format.size());
const auto & error_msg = CHDB::chdb_result_error_string(result);
if (!error_msg.empty())
throw std::runtime_error(std::string(error_msg));
if (!(chunk_result = dynamic_cast<CHDB::ChunkQueryResult *>(reinterpret_cast<CHDB::QueryResult *>(result))))
throw std::runtime_error("Expected ChunkQueryResult for dataframe format");
}
CHDB::PandasDataFrameBuilder builder(*chunk_result);
auto df = builder.getDataFrame();
return df;
}
std::string connection_wrapper::generate_sql(const std::string & prompt)
{
#if USE_CLIENT_AI
if (!ai_config.has_value())
ai_config = DB::AIConfiguration{};
try
{
if (!ai_processor)
ai_processor = std::make_unique<AIQueryProcessor>(conn, *ai_config);
return ai_processor->generateSQL(prompt);
}
catch (const std::exception & e)
{
throw std::runtime_error(std::string("AI SQL generation failed: ") + e.what());
}
#else
(void)prompt;
throw std::runtime_error("AI SQL generation is not available in this build. Rebuild with USE_CLIENT_AI enabled.");
#endif
}
streaming_query_result * connection_wrapper::send_query(const std::string & query_str, const std::string & format, const py::dict & params)
{
const auto parsed_params = parseParametersDict(params);
auto * client = getChdbClient(*conn);
QueryParameterGuard guard(client, parsed_params);
CHDB::cachePythonTablesFromQuery(reinterpret_cast<chdb_conn *>(*conn), query_str);
py::gil_scoped_release release;
auto * result = chdb_stream_query_n(*conn, query_str.data(), query_str.size(), format.data(), format.size());
const auto & error_msg = CHDB::chdb_result_error_string(result);
if (!error_msg.empty())
{
std::string msg_copy(error_msg);
chdb_destroy_query_result(result);
throw std::runtime_error(msg_copy);
}
return new streaming_query_result(result);
}
query_result * connection_wrapper::streaming_fetch_result(streaming_query_result * streaming_result)
{
py::gil_scoped_release release;
if (!streaming_result || !streaming_result->get_result())
return nullptr;
auto * result = chdb_stream_fetch_result(*conn, streaming_result->get_result());
const auto & error_msg = CHDB::chdb_result_error_string(result);
if (!error_msg.empty())
{
std::string msg_copy(error_msg);
chdb_destroy_query_result(result);
throw std::runtime_error(msg_copy);
}
return new query_result(result, false);
}
py::object connection_wrapper::streaming_fetch_df(streaming_query_result * streaming_result)
{
if (!streaming_result || !streaming_result->get_result())
return py::none();
chdb_result * result = nullptr;
CHDB::DataFrameQueryResult * chunk_result = nullptr;
SCOPE_EXIT({
if (result)
{
chdb_destroy_query_result(result);
CHDB::drainPyBorrowGuardQueue();
}
});
{
py::gil_scoped_release release;
result = chdb_stream_fetch_result(*conn, streaming_result->get_result());
const auto & error_msg = CHDB::chdb_result_error_string(result);
if (!error_msg.empty())
throw std::runtime_error(std::string(CHDB::chdb_result_error_string(result)));
if (!(chunk_result = dynamic_cast<CHDB::DataFrameQueryResult *>(reinterpret_cast<CHDB::QueryResult*>(result))))
throw std::runtime_error("Expected DataFrameQueryResult for dataframe format");
}
py::handle df_handle = chunk_result->dataframe;
return py::reinterpret_steal<py::object>(df_handle);
}
void connection_wrapper::streaming_cancel_query(streaming_query_result * streaming_result)
{
py::gil_scoped_release release;
if (!streaming_result || !streaming_result->get_result())
return;
chdb_stream_cancel_query(*conn, streaming_result->get_result());
}
streaming_insert_result * connection_wrapper::send_insert(const std::string & query_str, const std::string & format)
{
py::gil_scoped_release release;
auto * stream = chdb_stream_insert_n(*conn, query_str.data(), query_str.size(), format.data(), format.size());
auto * err = chdb_stream_insert_error(stream);
if (err)
{
std::string msg_copy(err);
chdb_destroy_insert_stream(stream);
throw std::runtime_error(msg_copy);
}
return new streaming_insert_result(stream);
}
void connection_wrapper::insert_append(streaming_insert_result * ins, const py::bytes & data)
{
if (!ins || !ins->get_stream())
throw std::runtime_error("Invalid insert stream");
/// Borrow the buffer under the GIL (py::bytes accessors need it), then
/// release the GIL for the (potentially blocking, backpressured) append.
char * buffer = nullptr;
Py_ssize_t length = 0;
if (PyBytes_AsStringAndSize(data.ptr(), &buffer, &length) != 0)
throw std::runtime_error("send_insert append expects bytes");
chdb_insert_stream stream = ins->get_stream();
chdb_state state;
{
py::gil_scoped_release release;
state = chdb_stream_append(stream, buffer, static_cast<size_t>(length));
}
if (state != CHDBSuccess)
{
auto * err = chdb_stream_insert_error(stream);
throw std::runtime_error(err ? err : "streaming insert append failed");
}
}
query_result * connection_wrapper::insert_done(streaming_insert_result * ins)
{
if (!ins || !ins->get_stream())
throw std::runtime_error("Invalid insert stream");
chdb_result * result = nullptr;
{
py::gil_scoped_release release;
result = chdb_stream_done(ins->get_stream());
}
const auto & error_msg = CHDB::chdb_result_error_string(result);
if (!error_msg.empty())
{
std::string msg_copy(error_msg);
chdb_destroy_query_result(result);
throw std::runtime_error(msg_copy);
}
return new query_result(result, false);
}
void connection_wrapper::insert_cancel(streaming_insert_result * ins)
{
py::gil_scoped_release release;
if (!ins || !ins->get_stream())
return;
chdb_stream_cancel_insert(ins->get_stream());
}
namespace
{
/// backup_database and restore_database return nothing, so the result exists
/// only to carry an error. Raise it if there is one, and drop the result
/// either way.
void raiseOnEngineError(chdb_result * result)
{
const auto & error_msg = CHDB::chdb_result_error_string(result);
if (error_msg.empty())
{
chdb_destroy_query_result(result);
return;
}
std::string msg_copy(error_msg);
chdb_destroy_query_result(result);
throw std::runtime_error(msg_copy);
}
}
/// close() sets conn to nullptr, so every entry point has to look before it
/// dereferences -- otherwise using a closed connection segfaults the
/// interpreter instead of raising.
void connection_wrapper::requireOpen() const
{
if (!conn)
throw std::runtime_error("Connection is closed");
}
void connection_wrapper::backup_database(
const std::string & database, const std::string & file_path, const std::string & base_file_path)
{
requireOpen();
py::gil_scoped_release release;
raiseOnEngineError(chdb_backup_database_n(
*conn,
database.data(),
database.size(),
file_path.data(),
file_path.size(),
base_file_path.empty() ? nullptr : base_file_path.data(),
base_file_path.size()));
}
void connection_wrapper::restore_database(const std::string & database, const std::string & file_path)
{
requireOpen();
py::gil_scoped_release release;
raiseOnEngineError(
chdb_restore_database_n(*conn, database.data(), database.size(), file_path.data(), file_path.size()));
}
py::dict connection_wrapper::classify_query(const std::string & sql, const std::string & target_database)
{
requireOpen();
chdb_query_analysis_v1 analysis{};
analysis.struct_size = sizeof(analysis);
{
py::gil_scoped_release release;
if (chdb_classify_query_n(
*conn,
sql.data(),
sql.size(),
target_database.empty() ? nullptr : target_database.data(),
target_database.size(),
&analysis)
!= CHDBSuccess)
throw std::runtime_error("Invalid or closed connection");
}
py::dict out;
out["query_class"] = static_cast<chdb_query_class>(analysis.query_class);
out["statement_count"] = analysis.statement_count;
out["has_secrets"] = (analysis.flags & CHDB_QUERY_HAS_SECRETS) != 0;
out["writes_only_target_database"] = (analysis.flags & CHDB_QUERY_WRITES_ONLY_TARGET_DATABASE) != 0;
out["changes_database_lifecycle"] = (analysis.flags & CHDB_QUERY_CHANGES_DATABASE_LIFECYCLE) != 0;
return out;
}
#if USE_CLIENT_AI
void connection_wrapper::applyAIParams(std::map<std::string, std::string> & params)
{
DB::AIConfiguration config;
auto consume_string = [&](const std::string & target, std::string DB::AIConfiguration::* field)
{
for (auto it = params.begin(); it != params.end();)
{
if (Poco::toLower(it->first) == target)
{
if (!it->second.empty())
{
if ((config.*field).empty())
config.*field = it->second;
}
it = params.erase(it);
}
else
{
++it;
}
}
};
auto consume_double = [&](const std::string & target, std::optional<double> DB::AIConfiguration::* field)
{
for (auto it = params.begin(); it != params.end();)
{
if (Poco::toLower(it->first) == target)
{
if (!it->second.empty())
{
try
{
config.*field = std::stod(it->second);
}
catch (...)
{
}
}
it = params.erase(it);
}
else
{
++it;
}
}
};
auto consume_size_t = [&](const std::string & target, size_t DB::AIConfiguration::* field)
{
for (auto it = params.begin(); it != params.end();)
{
if (Poco::toLower(it->first) == target)
{
if (!it->second.empty())
{
try
{
config.*field = static_cast<size_t>(std::stoul(it->second));
}
catch (...)
{
}
}
it = params.erase(it);
}
else
{
++it;
}
}
};
auto consume_bool = [&](const std::string & target, bool DB::AIConfiguration::* field)
{
for (auto it = params.begin(); it != params.end();)
{
if (Poco::toLower(it->first) == target)
{
if (!it->second.empty())
{
std::string val = Poco::toLower(it->second);
if (val == "1" || val == "true" || val == "yes" || val == "on")
config.*field = true;
else if (val == "0" || val == "false" || val == "no" || val == "off")
config.*field = false;
}
it = params.erase(it);
}
else
{
++it;
}
}
};
consume_string("ai_api_key", &DB::AIConfiguration::api_key);
consume_string("ai_base_url", &DB::AIConfiguration::base_url);
consume_string("ai_model", &DB::AIConfiguration::model);
consume_string("ai_provider", &DB::AIConfiguration::provider);
consume_double("ai_temperature", &DB::AIConfiguration::temperature);
consume_size_t("ai_max_tokens", &DB::AIConfiguration::max_tokens);
consume_size_t("ai_timeout_seconds", &DB::AIConfiguration::timeout_seconds);
consume_string("ai_system_prompt", &DB::AIConfiguration::system_prompt);
consume_size_t("ai_max_steps", &DB::AIConfiguration::max_steps);
consume_bool("ai_enable_schema_access", &DB::AIConfiguration::enable_schema_access);
ai_config = config;
}
#endif
void cursor_wrapper::execute(const std::string & query_str)
{
release_result();
CHDB::cachePythonTablesFromQuery(reinterpret_cast<chdb_conn *>(conn->get_conn()), query_str);
// Use JSONCompactEachRowWithNamesAndTypes format for better type support
py::gil_scoped_release release;
current_result = chdb_query_n(conn->get_conn(), query_str.data(), query_str.size(), CURSOR_DEFAULT_FORMAT, CURSOR_DEFAULT_FORMAT_LEN);
}
/// Cleanup function to be called before Python interpreter exits.
/// This ensures JIT cache is cleared before static CHJIT instances are destroyed.
static void chdb_cleanup_at_exit()
{
#if USE_EMBEDDED_COMPILER
try
{
if (auto * cache = DB::CompiledExpressionCacheFactory::instance().tryGetCache())
cache->clear();
}
catch (...)
{
// Ignore errors during cleanup at exit
}
#endif
}
#ifdef CHDB_FREE_THREADING
PYBIND11_MODULE(_chdb, m, py::mod_gil_not_used())
#else
PYBIND11_MODULE(_chdb, m)
#endif
{
m.doc() = "chDB module for query function";
/// Register atexit handler to clean up JIT cache before interpreter exits.
/// This prevents use-after-free when CompiledFunctionHolder destructors
/// try to access already-destroyed static CHJIT instances.
py::module_::import("atexit").attr("register")(py::cpp_function(&chdb_cleanup_at_exit));
/// py::arithmetic() is what makes the documented ordering usable: without
/// it a pybind enum has no __lt__, and max() over a batch's classes fails.
py::enum_<chdb_query_class>(
m,
"query_class",
"What a statement does to state that outlives it, as decided by the ClickHouse parser. "
"The members compare in ascending order of restriction, so a batch of statements "
"classifies as max() over its members",
py::arithmetic())
.value("READ_ONLY", CHDB_QUERY_READ_ONLY, "Leaves no trace: SELECT, SHOW, DESCRIBE, EXPLAIN, EXISTS, CHECK")
.value(
"MUTATING",
CHDB_QUERY_MUTATING,
"Changes a database, and BACKUP DATABASE captures the change: INSERT, CREATE, ALTER, "
"DROP, TRUNCATE, RENAME, UPDATE, DELETE, OPTIMIZE")
.value(
"MUTATING_GLOBAL",
CHDB_QUERY_MUTATING_GLOBAL,
"Persistent and worth replaying, but outside every database a checkpoint could "
"capture: global UDFs, named collections, workloads, resources, access management, "
"writes into the system database")
.value(
"CONTROL",
CHDB_QUERY_CONTROL,
"Session-scoped, so replaying is meaningless, or not something to issue through a "
"managed connection: USE, SET, ATTACH, DETACH, SYSTEM, BACKUP, RESTORE, KILL, "
"transactions, and writes outside the engine such as INTO OUTFILE")
.value("UNKNOWN", CHDB_QUERY_UNKNOWN, "Did not parse, or parsed into a statement this version does not classify");
py::class_<memoryview_wrapper>(m, "memoryview_wrapper")
.def(py::init<std::shared_ptr<local_result_wrapper>>(), py::return_value_policy::take_ownership)
.def("tobytes", &memoryview_wrapper::bytes)
.def("__len__", &memoryview_wrapper::size)
.def("size", &memoryview_wrapper::size)
.def("release", &memoryview_wrapper::release)
.def("view", &memoryview_wrapper::view);
py::class_<query_result>(m, "query_result")
.def(py::init<chdb_result *>(), py::return_value_policy::take_ownership)
/// Bound to the length-aware accessor on purpose. Binding query_result::data
/// (a char *) makes pybind11's type_caster<char> call strlen() on a buffer that
/// is exactly chdb_result_length() bytes and carries no terminator, which reads
/// out of bounds (AddressSanitizer: container-overflow). Same Python type as
/// before -- str -- just built from the length the engine reports.
.def("data", &query_result::str)
.def("bytes", &query_result::bytes)
.def("__str__", &query_result::str)
.def("__len__", &query_result::size)
.def("__repr__", &query_result::str)
.def("show", [](query_result & self) { py::print(self); })
.def("size", &query_result::size)
.def("rows_read", &query_result::rows_read)
.def("bytes_read", &query_result::bytes_read)
.def("storage_rows_read", &query_result::storage_rows_read)
.def("storage_bytes_read", &query_result::storage_bytes_read)
.def("elapsed", &query_result::elapsed)
.def("rows_written", &query_result::rows_written)
.def("bytes_written", &query_result::bytes_written)
.def("get_memview", &query_result::get_memview)
.def("has_error", &query_result::has_error)
.def("error_message", &query_result::error_message)
.def(
"__arrow_c_stream__",
[](query_result & self, py::object /*requested_schema*/)
{
if (self.has_error())
throw std::invalid_argument("query result carries an error: " + self.error_message().cast<std::string>());
return CHDB::exportArrowIPCAsCapsule(
self.data(), self.size(), std::static_pointer_cast<void>(self.get_result_wrapper()));
},
py::arg("requested_schema") = py::none(),
"Arrow PyCapsule interface: export the result as an ArrowArrayStream capsule.\n"
"Requires the query to have produced Arrow IPC output, i.e. output format\n"
"\"Arrow\" or \"ArrowStream\". The exported record batches reference the\n"
"result buffer directly (no copy) and keep the result alive until released.\n"
"Can be called multiple times; each call yields an independent stream.");
py::class_<streaming_query_result>(m, "streaming_query_result")
.def(py::init<chdb_result *>(), py::return_value_policy::take_ownership)
.def("has_error", &streaming_query_result::has_error)
.def("error_message", &streaming_query_result::error_message);