-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathpyconnection.cpp
More file actions
2449 lines (2193 loc) · 97.8 KB
/
pyconnection.cpp
File metadata and controls
2449 lines (2193 loc) · 97.8 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 "duckdb_python/pyconnection/pyconnection.hpp"
#include "duckdb/catalog/default/default_types.hpp"
#include "duckdb/common/arrow/arrow.hpp"
#include "duckdb/common/enums/file_compression_type.hpp"
#include "duckdb/common/enums/profiler_format.hpp"
#include "duckdb/common/printer.hpp"
#include "duckdb/common/types.hpp"
#include "duckdb/common/types/vector.hpp"
#include "duckdb/function/table/read_csv.hpp"
#include "duckdb/main/client_config.hpp"
#include "duckdb/main/client_context.hpp"
#include "duckdb/main/config.hpp"
#include "duckdb/main/db_instance_cache.hpp"
#include "duckdb/main/extension_helper.hpp"
#include "duckdb/main/prepared_statement.hpp"
#include "duckdb/main/relation/read_csv_relation.hpp"
#include "duckdb/main/relation/read_json_relation.hpp"
#include "duckdb/main/relation/value_relation.hpp"
#include "duckdb/main/relation/view_relation.hpp"
#include "duckdb/parser/expression/constant_expression.hpp"
#include "duckdb/parser/expression/function_expression.hpp"
#include "duckdb/parser/parsed_data/create_table_function_info.hpp"
#include "duckdb/parser/parser.hpp"
#include "duckdb/parser/statement/select_statement.hpp"
#include "duckdb/parser/tableref/subqueryref.hpp"
#include "duckdb/parser/tableref/table_function_ref.hpp"
#include "duckdb_python/arrow/arrow_array_stream.hpp"
#include "duckdb_python/map.hpp"
#include "duckdb_python/pandas/pandas_scan.hpp"
#include "duckdb_python/pyrelation.hpp"
#include "duckdb_python/pystatement.hpp"
#include "duckdb_python/pyresult.hpp"
#include "duckdb_python/python_conversion.hpp"
#include "duckdb_python/numpy/numpy_type.hpp"
#include "duckdb/main/prepared_statement.hpp"
#include "duckdb_python/jupyter_progress_bar_display.hpp"
#include "duckdb_python/pyfilesystem.hpp"
#include "duckdb/main/client_config.hpp"
#include "duckdb/function/table/read_csv.hpp"
#include "duckdb/common/enums/file_compression_type.hpp"
#include "duckdb/catalog/default/default_types.hpp"
#include "duckdb/main/relation/value_relation.hpp"
#include "duckdb_python/filesystem_object.hpp"
#include "duckdb/parser/parsed_data/create_scalar_function_info.hpp"
#include "duckdb/function/scalar_function.hpp"
#include "duckdb_python/pandas/pandas_scan.hpp"
#include "duckdb_python/python_objects.hpp"
#include "duckdb/function/function.hpp"
#include "duckdb_python/pybind11/conversions/exception_handling_enum.hpp"
#include "duckdb/parser/parsed_data/drop_info.hpp"
#include "duckdb/catalog/catalog_entry/scalar_function_catalog_entry.hpp"
#include "duckdb/main/pending_query_result.hpp"
#include "duckdb/parser/keyword_helper.hpp"
#include "duckdb_python/python_replacement_scan.hpp"
#include "duckdb/common/shared_ptr.hpp"
#include "duckdb/main/materialized_query_result.hpp"
#include "duckdb/main/stream_query_result.hpp"
#include "duckdb/main/relation/materialized_relation.hpp"
#include "duckdb/main/relation/query_relation.hpp"
#include "duckdb/parser/statement/load_statement.hpp"
#include "duckdb_python/expression/pyexpression.hpp"
#include <random>
#include "duckdb/common/printer.hpp"
namespace duckdb {
DefaultConnectionHolder DuckDBPyConnection::default_connection; // NOLINT: allow global
DBInstanceCache instance_cache; // NOLINT: allow global
shared_ptr<PythonImportCache> DuckDBPyConnection::import_cache = nullptr; // NOLINT: allow global
PythonEnvironmentType DuckDBPyConnection::environment = PythonEnvironmentType::NORMAL; // NOLINT: allow global
std::string DuckDBPyConnection::formatted_python_version = "";
DuckDBPyConnection::~DuckDBPyConnection() {
try {
py::gil_scoped_release gil;
// Release any structures that do not need to hold the GIL here
con.SetDatabase(nullptr);
con.SetConnection(nullptr);
} catch (...) { // NOLINT
}
}
unique_ptr<DuckDBPyRelation> DuckDBPyConnection::CreateRelation(shared_ptr<Relation> rel) {
auto py_rel = make_uniq<DuckDBPyRelation>(std::move(rel));
py::gil_scoped_acquire gil;
py_rel->SetConnectionOwner(py::cast(shared_from_this()));
return py_rel;
}
unique_ptr<DuckDBPyRelation> DuckDBPyConnection::CreateRelation(shared_ptr<DuckDBPyResult> result) {
auto py_rel = make_uniq<DuckDBPyRelation>(std::move(result));
py::gil_scoped_acquire gil;
py_rel->SetConnectionOwner(py::cast(shared_from_this()));
return py_rel;
}
void DuckDBPyConnection::DetectEnvironment() {
// Get the formatted Python version
py::module_ sys = py::module_::import("sys");
py::object version_info = sys.attr("version_info");
int major = py::cast<int>(version_info.attr("major"));
int minor = py::cast<int>(version_info.attr("minor"));
DuckDBPyConnection::formatted_python_version = std::to_string(major) + "." + std::to_string(minor);
// If __main__ does not have a __file__ attribute, we are in interactive mode
auto main_module = py::module_::import("__main__");
if (py::hasattr(main_module, "__file__")) {
return;
}
DuckDBPyConnection::environment = PythonEnvironmentType::INTERACTIVE;
if (!ModuleIsLoaded<IpythonCacheItem>()) {
return;
}
// Check to see if we are in a Jupyter Notebook
auto &import_cache_py = *DuckDBPyConnection::ImportCache();
auto get_ipython = import_cache_py.IPython.get_ipython();
if (get_ipython.ptr() == nullptr) {
// Could either not load the IPython module, or it has no 'get_ipython' attribute
return;
}
auto ipython = get_ipython();
if (!py::hasattr(ipython, "config")) {
return;
}
py::dict ipython_config = ipython.attr("config");
if (ipython_config.contains("IPKernelApp")) {
DuckDBPyConnection::environment = PythonEnvironmentType::JUPYTER;
}
return;
}
bool DuckDBPyConnection::DetectAndGetEnvironment() {
DuckDBPyConnection::DetectEnvironment();
return DuckDBPyConnection::IsInteractive();
}
bool DuckDBPyConnection::IsJupyter() {
return DuckDBPyConnection::environment == PythonEnvironmentType::JUPYTER;
}
std::string DuckDBPyConnection::FormattedPythonVersion() {
return DuckDBPyConnection::formatted_python_version;
}
// NOTE: this function is generated by tools/pythonpkg/scripts/generate_connection_methods.py.
// Do not edit this function manually, your changes will be overwritten!
static void InitializeConnectionMethods(py::class_<DuckDBPyConnection, shared_ptr<DuckDBPyConnection>> &m) {
m.def("cursor", &DuckDBPyConnection::Cursor, "Create a duplicate of the current connection");
m.def("register_filesystem", &DuckDBPyConnection::RegisterFilesystem, "Register a fsspec compliant filesystem",
py::arg("filesystem"));
m.def("unregister_filesystem", &DuckDBPyConnection::UnregisterFilesystem, "Unregister a filesystem",
py::arg("name"));
m.def("list_filesystems", &DuckDBPyConnection::ListFilesystems,
"List registered filesystems, including builtin ones");
m.def("filesystem_is_registered", &DuckDBPyConnection::FileSystemIsRegistered,
"Check if a filesystem with the provided name is currently registered", py::arg("name"));
m.def("create_function", &DuckDBPyConnection::RegisterScalarUDF,
"Create a DuckDB function out of the passing in Python function so it can be used in queries",
py::arg("name"), py::arg("function"), py::arg("parameters") = py::none(), py::arg("return_type") = py::none(),
py::kw_only(), py::arg("type") = PythonUDFType::NATIVE,
py::arg("null_handling") = FunctionNullHandling::DEFAULT_NULL_HANDLING,
py::arg("exception_handling") = PythonExceptionHandling::FORWARD_ERROR, py::arg("side_effects") = false);
m.def("remove_function", &DuckDBPyConnection::UnregisterUDF, "Remove a previously created function",
py::arg("name"));
m.def("sqltype", &DuckDBPyConnection::Type, "Create a type object by parsing the 'type_str' string",
py::arg("type_str"));
m.def("dtype", &DuckDBPyConnection::Type, "Create a type object by parsing the 'type_str' string",
py::arg("type_str"));
m.def("type", &DuckDBPyConnection::Type, "Create a type object by parsing the 'type_str' string",
py::arg("type_str"));
m.def("array_type", &DuckDBPyConnection::ArrayType, "Create an array type object of 'type'",
py::arg("type").none(false), py::arg("size"));
m.def("list_type", &DuckDBPyConnection::ListType, "Create a list type object of 'type'",
py::arg("type").none(false));
m.def("union_type", &DuckDBPyConnection::UnionType, "Create a union type object from 'members'",
py::arg("members").none(false));
m.def("string_type", &DuckDBPyConnection::StringType, "Create a string type with an optional collation",
py::arg("collation") = "");
m.def("enum_type", &DuckDBPyConnection::EnumType,
"Create an enum type of underlying 'type', consisting of the list of 'values'", py::arg("name"),
py::arg("type"), py::arg("values"));
m.def("decimal_type", &DuckDBPyConnection::DecimalType, "Create a decimal type with 'width' and 'scale'",
py::arg("width"), py::arg("scale"));
m.def("struct_type", &DuckDBPyConnection::StructType, "Create a struct type object from 'fields'",
py::arg("fields"));
m.def("row_type", &DuckDBPyConnection::StructType, "Create a struct type object from 'fields'", py::arg("fields"));
m.def("map_type", &DuckDBPyConnection::MapType, "Create a map type object from 'key_type' and 'value_type'",
py::arg("key").none(false), py::arg("value").none(false));
m.def("duplicate", &DuckDBPyConnection::Cursor, "Create a duplicate of the current connection");
m.def("execute", &DuckDBPyConnection::Execute,
"Execute the given SQL query, optionally using prepared statements with parameters set", py::arg("query"),
py::arg("parameters") = py::none());
m.def("executemany", &DuckDBPyConnection::ExecuteMany,
"Execute the given prepared statement multiple times using the list of parameter sets in parameters",
py::arg("query"), py::arg("parameters") = py::none());
m.def("close", &DuckDBPyConnection::Close, "Close the connection");
m.def("interrupt", &DuckDBPyConnection::Interrupt, "Interrupt pending operations");
m.def("query_progress", &DuckDBPyConnection::QueryProgress, "Query progress of pending operation");
m.def("fetchone", &DuckDBPyConnection::FetchOne, "Fetch a single row from a result following execute");
m.def("fetchmany", &DuckDBPyConnection::FetchMany, "Fetch the next set of rows from a result following execute",
py::arg("size") = 1);
m.def("fetchall", &DuckDBPyConnection::FetchAll, "Fetch all rows from a result following execute");
m.def("fetchnumpy", &DuckDBPyConnection::FetchNumpy, "Fetch a result as list of NumPy arrays following execute");
m.def("fetchdf", &DuckDBPyConnection::FetchDF, "Fetch a result as DataFrame following execute()", py::kw_only(),
py::arg("date_as_object") = false);
m.def("fetch_df", &DuckDBPyConnection::FetchDF, "Fetch a result as DataFrame following execute()", py::kw_only(),
py::arg("date_as_object") = false);
m.def("df", &DuckDBPyConnection::FetchDF, "Fetch a result as DataFrame following execute()", py::kw_only(),
py::arg("date_as_object") = false);
m.def("fetch_df_chunk", &DuckDBPyConnection::FetchDFChunk,
"Fetch a chunk of the result as DataFrame following execute()", py::arg("vectors_per_chunk") = 1,
py::kw_only(), py::arg("date_as_object") = false);
m.def("pl", &DuckDBPyConnection::FetchPolars, "Fetch a result as Polars DataFrame following execute()",
py::arg("rows_per_batch") = 1000000, py::kw_only(), py::arg("lazy") = false);
m.def("to_arrow_table", &DuckDBPyConnection::FetchArrow, "Fetch a result as Arrow table following execute()",
py::arg("batch_size") = 1000000);
m.def("to_arrow_reader", &DuckDBPyConnection::FetchRecordBatchReader,
"Fetch an Arrow RecordBatchReader following execute()", py::arg("batch_size") = 1000000);
m.def(
"fetch_arrow_table",
[](DuckDBPyConnection &self, idx_t rows_per_batch) {
PyErr_WarnEx(PyExc_DeprecationWarning, "fetch_arrow_table() is deprecated, use to_arrow_table() instead.",
0);
return self.FetchArrow(rows_per_batch);
},
"Fetch a result as Arrow table following execute()", py::arg("rows_per_batch") = 1000000);
m.def(
"fetch_record_batch",
[](DuckDBPyConnection &self, idx_t rows_per_batch) {
PyErr_WarnEx(PyExc_DeprecationWarning, "fetch_record_batch() is deprecated, use to_arrow_reader() instead.",
0);
return self.FetchRecordBatchReader(rows_per_batch);
},
"Fetch an Arrow RecordBatchReader following execute()", py::arg("rows_per_batch") = 1000000);
m.def("arrow", &DuckDBPyConnection::FetchRecordBatchReader,
"Alias of to_arrow_reader(). We recommend using to_arrow_reader() instead.",
py::arg("rows_per_batch") = 1000000);
m.def("torch", &DuckDBPyConnection::FetchPyTorch, "Fetch a result as dict of PyTorch Tensors following execute()");
m.def("tf", &DuckDBPyConnection::FetchTF, "Fetch a result as dict of TensorFlow Tensors following execute()");
m.def("begin", &DuckDBPyConnection::Begin, "Start a new transaction");
m.def("commit", &DuckDBPyConnection::Commit, "Commit changes performed within a transaction");
m.def("rollback", &DuckDBPyConnection::Rollback, "Roll back changes performed within a transaction");
m.def("checkpoint", &DuckDBPyConnection::Checkpoint,
"Synchronizes data in the write-ahead log (WAL) to the database data file (no-op for in-memory connections)");
m.def("append", &DuckDBPyConnection::Append, "Append the passed DataFrame to the named table",
py::arg("table_name"), py::arg("df"), py::kw_only(), py::arg("by_name") = false);
m.def("register", &DuckDBPyConnection::RegisterPythonObject,
"Register the passed Python Object value for querying with a view", py::arg("view_name"),
py::arg("python_object"));
m.def("unregister", &DuckDBPyConnection::UnregisterPythonObject, "Unregister the view name", py::arg("view_name"));
m.def("table", &DuckDBPyConnection::Table, "Create a relation object for the named table", py::arg("table_name"));
m.def("view", &DuckDBPyConnection::View, "Create a relation object for the named view", py::arg("view_name"));
m.def("values", &DuckDBPyConnection::Values, "Create a relation object from the passed values");
m.def("table_function", &DuckDBPyConnection::TableFunction,
"Create a relation object from the named table function with given parameters", py::arg("name"),
py::arg("parameters") = py::none());
m.def("read_json", &DuckDBPyConnection::ReadJSON, "Create a relation object from the JSON file in 'name'",
py::arg("path_or_buffer"), py::kw_only(), py::arg("columns") = py::none(),
py::arg("sample_size") = py::none(), py::arg("maximum_depth") = py::none(), py::arg("records") = py::none(),
py::arg("format") = py::none(), py::arg("date_format") = py::none(), py::arg("timestamp_format") = py::none(),
py::arg("compression") = py::none(), py::arg("maximum_object_size") = py::none(),
py::arg("ignore_errors") = py::none(), py::arg("convert_strings_to_integers") = py::none(),
py::arg("field_appearance_threshold") = py::none(), py::arg("map_inference_threshold") = py::none(),
py::arg("maximum_sample_files") = py::none(), py::arg("filename") = py::none(),
py::arg("hive_partitioning") = py::none(), py::arg("union_by_name") = py::none(),
py::arg("hive_types") = py::none(), py::arg("hive_types_autocast") = py::none());
m.def("extract_statements", &DuckDBPyConnection::ExtractStatements,
"Parse the query string and extract the Statement object(s) produced", py::arg("query"));
m.def("sql", &DuckDBPyConnection::RunQuery,
"Run a SQL query. If it is a SELECT statement, create a relation object from the given SQL query, otherwise "
"run the query as-is.",
py::arg("query"), py::kw_only(), py::arg("alias") = "", py::arg("params") = py::none());
m.def("query", &DuckDBPyConnection::RunQuery,
"Run a SQL query. If it is a SELECT statement, create a relation object from the given SQL query, otherwise "
"run the query as-is.",
py::arg("query"), py::kw_only(), py::arg("alias") = "", py::arg("params") = py::none());
m.def("from_query", &DuckDBPyConnection::RunQuery,
"Run a SQL query. If it is a SELECT statement, create a relation object from the given SQL query, otherwise "
"run the query as-is.",
py::arg("query"), py::kw_only(), py::arg("alias") = "", py::arg("params") = py::none());
m.def("read_csv", &DuckDBPyConnection::ReadCSV, "Create a relation object from the CSV file in 'name'",
py::arg("path_or_buffer"), py::kw_only());
m.def("from_csv_auto", &DuckDBPyConnection::ReadCSV, "Create a relation object from the CSV file in 'name'",
py::arg("path_or_buffer"), py::kw_only());
m.def("from_df", &DuckDBPyConnection::FromDF, "Create a relation object from the DataFrame in df", py::arg("df"));
m.def("from_arrow", &DuckDBPyConnection::FromArrow, "Create a relation object from an Arrow object",
py::arg("arrow_object"));
m.def("from_parquet", &DuckDBPyConnection::FromParquet,
"Create a relation object from the Parquet files in file_glob", py::arg("file_glob"),
py::arg("binary_as_string") = false, py::kw_only(), py::arg("file_row_number") = false,
py::arg("filename") = false, py::arg("hive_partitioning") = false, py::arg("union_by_name") = false,
py::arg("compression") = py::none());
m.def("read_parquet", &DuckDBPyConnection::FromParquet,
"Create a relation object from the Parquet files in file_glob", py::arg("file_glob"),
py::arg("binary_as_string") = false, py::kw_only(), py::arg("file_row_number") = false,
py::arg("filename") = false, py::arg("hive_partitioning") = false, py::arg("union_by_name") = false,
py::arg("compression") = py::none());
m.def("from_parquet", &DuckDBPyConnection::FromParquets,
"Create a relation object from the Parquet files in file_globs", py::arg("file_globs"),
py::arg("binary_as_string") = false, py::kw_only(), py::arg("file_row_number") = false,
py::arg("filename") = false, py::arg("hive_partitioning") = false, py::arg("union_by_name") = false,
py::arg("compression") = py::none());
m.def("read_parquet", &DuckDBPyConnection::FromParquets,
"Create a relation object from the Parquet files in file_globs", py::arg("file_globs"),
py::arg("binary_as_string") = false, py::kw_only(), py::arg("file_row_number") = false,
py::arg("filename") = false, py::arg("hive_partitioning") = false, py::arg("union_by_name") = false,
py::arg("compression") = py::none());
m.def("get_table_names", &DuckDBPyConnection::GetTableNames, "Extract the required table names from a query",
py::arg("query"), py::kw_only(), py::arg("qualified") = false);
m.def("install_extension", &DuckDBPyConnection::InstallExtension,
"Install an extension by name, with an optional version and/or repository to get the extension from",
py::arg("extension"), py::kw_only(), py::arg("force_install") = false, py::arg("repository") = py::none(),
py::arg("repository_url") = py::none(), py::arg("version") = py::none());
m.def("load_extension", &DuckDBPyConnection::LoadExtension, "Load an installed extension", py::arg("extension"));
m.def("get_profiling_information", &DuckDBPyConnection::GetProfilingInformation,
"Get profiling information for a query", py::arg("format") = "json");
m.def("enable_profiling", &DuckDBPyConnection::EnableProfiling, "Enable profiling for subsequent queries");
m.def("disable_profiling", &DuckDBPyConnection::DisableProfiling, "Disable profiling for subsequent queries");
} // END_OF_CONNECTION_METHODS
void DuckDBPyConnection::UnregisterFilesystem(const py::str &name) {
auto &database = con.GetDatabase();
auto &fs = database.GetFileSystem();
fs.ExtractSubSystem(name);
}
void DuckDBPyConnection::RegisterFilesystem(AbstractFileSystem filesystem) {
PythonGILWrapper gil_wrapper;
auto &database = con.GetDatabase();
if (!py::isinstance<AbstractFileSystem>(filesystem)) {
throw InvalidInputException("Bad filesystem instance");
}
auto &fs = database.GetFileSystem();
auto protocol = filesystem.attr("protocol");
if (protocol.is_none() || py::str("abstract").equal(protocol)) {
throw InvalidInputException("Must provide concrete fsspec implementation");
}
vector<string> protocols;
if (py::isinstance<py::str>(protocol)) {
protocols.push_back(py::str(protocol));
} else {
for (const auto &sub_protocol : protocol) {
protocols.push_back(py::str(sub_protocol));
}
}
fs.RegisterSubSystem(make_uniq<PythonFilesystem>(std::move(protocols), std::move(filesystem)));
}
py::list DuckDBPyConnection::ListFilesystems() {
auto &database = con.GetDatabase();
auto subsystems = database.GetFileSystem().ListSubSystems();
py::list names;
for (auto &name : subsystems) {
names.append(py::str(name));
}
return names;
}
py::str DuckDBPyConnection::GetProfilingInformation(const py::str &format) {
// We want to expose ProfilerPrintFormat as a string to Python users
ProfilerPrintFormat format_enum;
if (format == "query_tree") {
format_enum = ProfilerPrintFormat::QUERY_TREE;
} else if (format == "json") {
format_enum = ProfilerPrintFormat::JSON;
} else if (format == "query_tree_optimizer") {
format_enum = ProfilerPrintFormat::QUERY_TREE_OPTIMIZER;
} else if (format == "no_output") {
format_enum = ProfilerPrintFormat::NO_OUTPUT;
} else if (format == "html") {
format_enum = ProfilerPrintFormat::HTML;
} else if (format == "graphviz") {
format_enum = ProfilerPrintFormat::GRAPHVIZ;
} else {
throw InvalidInputException(
"Invalid ProfilerPrintFormat string: " + std::string(format) +
". Valid options are: query_tree, json, query_tree_optimizer, no_output, html, graphviz.");
}
auto &connection = con.GetConnection();
py::str profiling_info = connection.GetProfilingInformation(format_enum);
return profiling_info;
}
void DuckDBPyConnection::EnableProfiling() {
auto &connection = con.GetConnection();
connection.EnableProfiling();
}
void DuckDBPyConnection::DisableProfiling() {
auto &connection = con.GetConnection();
connection.DisableProfiling();
}
py::list DuckDBPyConnection::ExtractStatements(const string &query) {
py::list result;
auto &connection = con.GetConnection();
auto statements = connection.ExtractStatements(query);
for (auto &statement : statements) {
result.append(make_uniq<DuckDBPyStatement>(std::move(statement)));
}
return result;
}
bool DuckDBPyConnection::FileSystemIsRegistered(const string &name) {
auto &database = con.GetDatabase();
auto subsystems = database.GetFileSystem().ListSubSystems();
return std::find(subsystems.begin(), subsystems.end(), name) != subsystems.end();
}
shared_ptr<DuckDBPyConnection> DuckDBPyConnection::UnregisterUDF(const string &name) {
auto entry = registered_functions.find(name);
if (entry == registered_functions.end()) {
// Not registered or already unregistered
throw InvalidInputException("No function by the name of '%s' was found in the list of registered functions",
name);
}
auto &connection = con.GetConnection();
auto &context = *connection.context;
context.RunFunctionInTransaction([&]() {
// create function
auto &catalog = Catalog::GetCatalog(context, SYSTEM_CATALOG);
DropInfo info;
info.type = CatalogType::SCALAR_FUNCTION_ENTRY;
info.name = name;
info.allow_drop_internal = true;
info.cascade = false;
info.if_not_found = OnEntryNotFound::THROW_EXCEPTION;
catalog.DropEntry(context, info);
});
registered_functions.erase(entry);
return shared_from_this();
}
shared_ptr<DuckDBPyConnection>
DuckDBPyConnection::RegisterScalarUDF(const string &name, const py::function &udf, const py::object ¶meters_p,
const shared_ptr<DuckDBPyType> &return_type_p, PythonUDFType type,
FunctionNullHandling null_handling, PythonExceptionHandling exception_handling,
bool side_effects) {
auto &connection = con.GetConnection();
auto &context = *connection.context;
if (context.transaction.HasActiveTransaction()) {
context.CancelTransaction();
}
if (registered_functions.find(name) != registered_functions.end()) {
throw NotImplementedException("A function by the name of '%s' is already created, creating multiple "
"functions with the same name is not supported yet, please remove it first",
name);
}
auto scalar_function = CreateScalarUDF(name, udf, parameters_p, return_type_p, type == PythonUDFType::ARROW,
null_handling, exception_handling, side_effects);
CreateScalarFunctionInfo info(scalar_function);
context.RegisterFunction(info);
auto dependency = make_uniq<ExternalDependency>();
dependency->AddDependency("function", PythonDependencyItem::Create(udf));
registered_functions[name] = std::move(dependency);
return shared_from_this();
}
void DuckDBPyConnection::Initialize(py::handle &m) {
auto connection_module =
py::class_<DuckDBPyConnection, shared_ptr<DuckDBPyConnection>>(m, "DuckDBPyConnection", py::module_local());
connection_module.def("__enter__", &DuckDBPyConnection::Enter)
.def("__exit__", &DuckDBPyConnection::Exit, py::arg("exc_type"), py::arg("exc"), py::arg("traceback"));
connection_module.def("__del__", &DuckDBPyConnection::Close);
InitializeConnectionMethods(connection_module);
connection_module.def("subcursor", &DuckDBPyConnection::Subcursor,
"Create a cursor sharing the same connection and transaction");
connection_module.def_property_readonly("description", &DuckDBPyConnection::GetDescription,
"Get result set attributes, mainly column names");
connection_module.def_property_readonly("rowcount", &DuckDBPyConnection::GetRowcount, "Get result set row count");
PyDateTime_IMPORT; // NOLINT
DuckDBPyConnection::ImportCache();
}
shared_ptr<DuckDBPyConnection> DuckDBPyConnection::ExecuteMany(const py::object &query, py::object params_p) {
py::gil_scoped_acquire gil;
con.SetResult(nullptr);
if (params_p.is_none()) {
params_p = py::list();
}
auto statements = GetStatements(query);
if (statements.empty()) {
// TODO: should we throw?
return nullptr;
}
auto last_statement = std::move(statements.back());
statements.pop_back();
// First immediately execute any preceding statements (if any)
// FIXME: DBAPI says to not accept an 'executemany' call with multiple statements
ExecuteImmediately(std::move(statements));
auto prep = PrepareQuery(std::move(last_statement));
if (!py::is_list_like(params_p)) {
throw InvalidInputException("executemany requires a list of parameter sets to be provided");
}
auto outer_list = py::list(params_p);
if (outer_list.empty()) {
throw InvalidInputException("executemany requires a non-empty list of parameter sets to be provided");
}
unique_ptr<QueryResult> query_result;
// Execute once for every set of parameters that are provided
for (auto ¶meters : outer_list) {
auto params = py::reinterpret_borrow<py::object>(parameters);
query_result = ExecuteInternal(*prep, std::move(params));
}
// Set the internal 'result' object
if (query_result) {
// Don't use CreateRelation here — the result is stored inside the connection,
// so setting connection_owner would create a ref cycle (connection → result → connection).
con.SetResult(make_uniq<DuckDBPyRelation>(make_shared_ptr<DuckDBPyResult>(std::move(query_result))));
}
return shared_from_this();
}
unique_ptr<QueryResult> DuckDBPyConnection::CompletePendingQuery(PendingQueryResult &pending_query) {
PendingExecutionResult execution_result;
if (pending_query.HasError()) {
pending_query.ThrowError();
}
while (!PendingQueryResult::IsResultReady(execution_result = pending_query.ExecuteTask())) {
{
py::gil_scoped_acquire gil;
if (PyErr_CheckSignals() != 0) {
throw std::runtime_error("Query interrupted");
}
}
if (execution_result == PendingExecutionResult::BLOCKED) {
pending_query.WaitForTask();
}
}
if (execution_result == PendingExecutionResult::EXECUTION_ERROR) {
pending_query.ThrowError();
}
return pending_query.Execute();
}
py::list TransformNamedParameters(const case_insensitive_map_t<idx_t> &named_param_map, const py::dict ¶ms) {
py::list new_params(params.size());
for (auto &item : params) {
const std::string &item_name = item.first.cast<std::string>();
auto entry = named_param_map.find(item_name);
if (entry == named_param_map.end()) {
throw InvalidInputException(
"Named parameters could not be transformed, because query string is missing named parameter '%s'",
item_name);
}
auto param_idx = entry->second;
// Add the value of the named parameter to the list
new_params[param_idx - 1] = item.second;
}
if (named_param_map.size() != params.size()) {
// One or more named parameters were expected, but not found
vector<string> missing_params;
missing_params.reserve(named_param_map.size());
for (auto &entry : named_param_map) {
auto &name = entry.first;
if (!params.contains(name)) {
missing_params.push_back(name);
}
}
auto message = StringUtil::Join(missing_params, ", ");
throw InvalidInputException("Not all named parameters have been located, missing: %s", message);
}
return new_params;
}
case_insensitive_map_t<BoundParameterData> TransformPreparedParameters(const py::object ¶ms,
optional_ptr<PreparedStatement> prep = {}) {
case_insensitive_map_t<BoundParameterData> named_values;
if (py::is_list_like(params)) {
if (prep && prep->named_param_map.size() != py::len(params)) {
if (py::len(params) == 0) {
throw InvalidInputException("Expected %d parameters, but none were supplied",
prep->named_param_map.size());
}
throw InvalidInputException("Prepared statement needs %d parameters, %d given",
prep->named_param_map.size(), py::len(params));
}
auto unnamed_values = DuckDBPyConnection::TransformPythonParamList(params);
for (idx_t i = 0; i < unnamed_values.size(); i++) {
auto &value = unnamed_values[i];
auto identifier = std::to_string(i + 1);
named_values[identifier] = BoundParameterData(std::move(value));
}
} else if (py::is_dict_like(params)) {
auto dict = py::cast<py::dict>(params);
named_values = DuckDBPyConnection::TransformPythonParamDict(dict);
} else {
throw InvalidInputException("Prepared parameters can only be passed as a list or a dictionary");
}
return named_values;
}
unique_ptr<PreparedStatement> DuckDBPyConnection::PrepareQuery(unique_ptr<SQLStatement> statement) {
auto &connection = con.GetConnection();
unique_ptr<PreparedStatement> prep;
{
D_ASSERT(py::gil_check());
py::gil_scoped_release release;
unique_lock<mutex> lock(*py_connection_lock);
prep = connection.Prepare(std::move(statement));
if (prep->HasError()) {
prep->error.Throw();
}
}
return prep;
}
unique_ptr<QueryResult> DuckDBPyConnection::ExecuteInternal(PreparedStatement &prep, py::object params) {
if (params.is_none()) {
params = py::list();
}
// Execute the prepared statement with the prepared parameters
auto named_values = TransformPreparedParameters(params, prep);
unique_ptr<QueryResult> res;
{
D_ASSERT(py::gil_check());
py::gil_scoped_release release;
unique_lock<std::mutex> lock(*py_connection_lock);
auto pending_query = prep.PendingQuery(named_values);
if (pending_query->HasError()) {
pending_query->ThrowError();
}
res = CompletePendingQuery(*pending_query);
if (res->HasError()) {
res->ThrowError();
}
}
return res;
}
unique_ptr<QueryResult> DuckDBPyConnection::PrepareAndExecuteInternal(unique_ptr<SQLStatement> statement,
py::object params) {
if (params.is_none()) {
params = py::list();
}
auto named_values = TransformPreparedParameters(params);
unique_ptr<QueryResult> res;
{
D_ASSERT(py::gil_check());
py::gil_scoped_release release;
unique_lock<std::mutex> lock(*py_connection_lock);
auto pending_query = con.GetConnection().PendingQuery(std::move(statement), named_values, true);
if (pending_query->HasError()) {
pending_query->ThrowError();
}
res = CompletePendingQuery(*pending_query);
if (res->HasError()) {
res->ThrowError();
}
}
return res;
}
vector<unique_ptr<SQLStatement>> DuckDBPyConnection::GetStatements(const py::object &query) {
shared_ptr<DuckDBPyStatement> statement_obj;
if (py::try_cast(query, statement_obj)) {
vector<unique_ptr<SQLStatement>> result;
result.push_back(statement_obj->GetStatement());
return result;
}
if (py::isinstance<py::str>(query)) {
auto &connection = con.GetConnection();
auto sql_query = std::string(py::str(query));
auto statements = connection.ExtractStatements(sql_query);
return std::move(statements);
}
throw InvalidInputException("Please provide either a DuckDBPyStatement or a string representing the query");
}
shared_ptr<DuckDBPyConnection> DuckDBPyConnection::ExecuteFromString(const string &query) {
return Execute(py::str(query));
}
shared_ptr<DuckDBPyConnection> DuckDBPyConnection::Execute(const py::object &query, py::object params) {
py::gil_scoped_acquire gil;
con.SetResult(nullptr);
auto statements = GetStatements(query);
if (statements.empty()) {
// TODO: should we throw?
return nullptr;
}
auto last_statement = std::move(statements.back());
statements.pop_back();
// First immediately execute any preceding statements (if any)
// FIXME: SQLites implementation says to not accept an 'execute' call with multiple statements
ExecuteImmediately(std::move(statements));
auto res = PrepareAndExecuteInternal(std::move(last_statement), std::move(params));
// Set the internal 'result' object
if (res) {
// Don't use CreateRelation here — the result is stored inside the connection,
// so setting connection_owner would create a ref cycle (connection → result → connection).
con.SetResult(make_uniq<DuckDBPyRelation>(make_shared_ptr<DuckDBPyResult>(std::move(res))));
}
return shared_from_this();
}
shared_ptr<DuckDBPyConnection> DuckDBPyConnection::Append(const string &name, const PandasDataFrame &value,
bool by_name) {
RegisterPythonObject("__append_df", value);
string columns = "";
if (by_name) {
auto df_columns = value.attr("columns");
vector<string> column_names;
for (auto &column : df_columns) {
column_names.push_back(std::string(py::str(column)));
}
columns += "(";
for (idx_t i = 0; i < column_names.size(); i++) {
auto &column = column_names[i];
if (i != 0) {
columns += ", ";
}
columns += StringUtil::Format("%s", SQLIdentifier(column));
}
columns += ")";
}
auto sql_query = StringUtil::Format("INSERT INTO %s %s SELECT * FROM __append_df", SQLIdentifier(name), columns);
return Execute(py::str(sql_query));
}
shared_ptr<DuckDBPyConnection> DuckDBPyConnection::RegisterPythonObject(const string &name,
const py::object &python_object) {
auto &connection = con.GetConnection();
auto &client = *connection.context;
auto object = PythonReplacementScan::ReplacementObject(python_object, name, client);
auto view_rel = make_shared_ptr<ViewRelation>(connection.context, std::move(object), name);
bool replace = registered_objects.count(name);
view_rel->CreateView(name, replace, true);
registered_objects.insert(name);
return shared_from_this();
}
static void ParseMultiFileOptions(named_parameter_map_t &options, const Optional<py::object> &filename,
const Optional<py::object> &hive_partitioning,
const Optional<py::object> &union_by_name, const Optional<py::object> &hive_types,
const Optional<py::object> &hive_types_autocast) {
if (!py::none().is(filename)) {
auto val = TransformPythonValue(filename);
options["filename"] = val;
}
if (!py::none().is(hive_types)) {
auto val = TransformPythonValue(hive_types);
options["hive_types"] = val;
}
if (!py::none().is(hive_partitioning)) {
if (!py::isinstance<py::bool_>(hive_partitioning)) {
string actual_type = py::str(py::type::of(hive_partitioning));
throw BinderException("read_json only accepts 'hive_partitioning' as a boolean, not '%s'", actual_type);
}
auto val = TransformPythonValue(hive_partitioning, LogicalTypeId::BOOLEAN);
options["hive_partitioning"] = val;
}
if (!py::none().is(union_by_name)) {
if (!py::isinstance<py::bool_>(union_by_name)) {
string actual_type = py::str(py::type::of(union_by_name));
throw BinderException("read_json only accepts 'union_by_name' as a boolean, not '%s'", actual_type);
}
auto val = TransformPythonValue(union_by_name, LogicalTypeId::BOOLEAN);
options["union_by_name"] = val;
}
if (!py::none().is(hive_types_autocast)) {
if (!py::isinstance<py::bool_>(hive_types_autocast)) {
string actual_type = py::str(py::type::of(hive_types_autocast));
throw BinderException("read_json only accepts 'hive_types_autocast' as a boolean, not '%s'", actual_type);
}
auto val = TransformPythonValue(hive_types_autocast, LogicalTypeId::BOOLEAN);
options["hive_types_autocast"] = val;
}
}
unique_ptr<DuckDBPyRelation> DuckDBPyConnection::ReadJSON(
const py::object &name_p, const Optional<py::object> &columns, const Optional<py::object> &sample_size,
const Optional<py::object> &maximum_depth, const Optional<py::str> &records, const Optional<py::str> &format,
const Optional<py::object> &date_format, const Optional<py::object> ×tamp_format,
const Optional<py::object> &compression, const Optional<py::object> &maximum_object_size,
const Optional<py::object> &ignore_errors, const Optional<py::object> &convert_strings_to_integers,
const Optional<py::object> &field_appearance_threshold, const Optional<py::object> &map_inference_threshold,
const Optional<py::object> &maximum_sample_files, const Optional<py::object> &filename,
const Optional<py::object> &hive_partitioning, const Optional<py::object> &union_by_name,
const Optional<py::object> &hive_types, const Optional<py::object> &hive_types_autocast) {
named_parameter_map_t options;
auto &connection = con.GetConnection();
auto path_like = GetPathLike(name_p);
auto &name = path_like.files;
auto file_like_object_wrapper = std::move(path_like.dependency);
ParseMultiFileOptions(options, filename, hive_partitioning, union_by_name, hive_types, hive_types_autocast);
if (!py::none().is(columns)) {
if (!py::is_dict_like(columns)) {
throw BinderException("read_json only accepts 'columns' as a dict[str, str]");
}
py::dict columns_dict = columns;
child_list_t<Value> struct_fields;
for (auto &kv : columns_dict) {
auto &column_name = kv.first;
auto &type = kv.second;
if (!py::isinstance<py::str>(column_name)) {
string actual_type = py::str(py::type::of(column_name));
throw BinderException("The provided column name must be a str, not of type '%s'", actual_type);
}
if (!py::isinstance<py::str>(type)) {
string actual_type = py::str(py::type::of(column_name));
throw BinderException("The provided column type must be a str, not of type '%s'", actual_type);
}
struct_fields.emplace_back(py::str(column_name), Value(py::str(type)));
}
auto dtype_struct = Value::STRUCT(std::move(struct_fields));
options["columns"] = std::move(dtype_struct);
}
if (!py::none().is(records)) {
if (!py::isinstance<py::str>(records)) {
string actual_type = py::str(py::type::of(records));
throw BinderException("read_json only accepts 'records' as a string, not '%s'", actual_type);
}
auto records_s = py::reinterpret_borrow<py::str>(records);
auto records_option = std::string(py::str(records_s));
options["records"] = Value(records_option);
}
if (!py::none().is(format)) {
if (!py::isinstance<py::str>(format)) {
string actual_type = py::str(py::type::of(format));
throw BinderException("read_json only accepts 'format' as a string, not '%s'", actual_type);
}
auto format_s = py::reinterpret_borrow<py::str>(format);
auto format_option = std::string(py::str(format_s));
options["format"] = Value(format_option);
}
if (!py::none().is(date_format)) {
if (!py::isinstance<py::str>(date_format)) {
string actual_type = py::str(py::type::of(date_format));
throw BinderException("read_json only accepts 'date_format' as a string, not '%s'", actual_type);
}
auto date_format_s = py::reinterpret_borrow<py::str>(date_format);
auto date_format_option = std::string(py::str(date_format_s));
options["date_format"] = Value(date_format_option);
}
if (!py::none().is(timestamp_format)) {
if (!py::isinstance<py::str>(timestamp_format)) {
string actual_type = py::str(py::type::of(timestamp_format));
throw BinderException("read_json only accepts 'timestamp_format' as a string, not '%s'", actual_type);
}
auto timestamp_format_s = py::reinterpret_borrow<py::str>(timestamp_format);
auto timestamp_format_option = std::string(py::str(timestamp_format_s));
options["timestamp_format"] = Value(timestamp_format_option);
}
if (!py::none().is(compression)) {
if (!py::isinstance<py::str>(compression)) {
string actual_type = py::str(py::type::of(compression));
throw BinderException("read_json only accepts 'compression' as a string, not '%s'", actual_type);
}
auto compression_s = py::reinterpret_borrow<py::str>(compression);
auto compression_option = std::string(py::str(compression_s));
options["compression"] = Value(compression_option);
}
if (!py::none().is(sample_size)) {
if (!py::isinstance<py::int_>(sample_size)) {
string actual_type = py::str(py::type::of(sample_size));
throw BinderException("read_json only accepts 'sample_size' as an integer, not '%s'", actual_type);
}
options["sample_size"] = Value::INTEGER(py::int_(sample_size));
}
if (!py::none().is(maximum_depth)) {
if (!py::isinstance<py::int_>(maximum_depth)) {
string actual_type = py::str(py::type::of(maximum_depth));
throw BinderException("read_json only accepts 'maximum_depth' as an integer, not '%s'", actual_type);
}
options["maximum_depth"] = Value::INTEGER(py::int_(maximum_depth));
}
if (!py::none().is(maximum_object_size)) {
if (!py::isinstance<py::int_>(maximum_object_size)) {
string actual_type = py::str(py::type::of(maximum_object_size));
throw BinderException("read_json only accepts 'maximum_object_size' as an unsigned integer, not '%s'",
actual_type);
}
auto val = TransformPythonValue(maximum_object_size, LogicalTypeId::UINTEGER);
options["maximum_object_size"] = val;
}
if (!py::none().is(ignore_errors)) {
if (!py::isinstance<py::bool_>(ignore_errors)) {
string actual_type = py::str(py::type::of(ignore_errors));
throw BinderException("read_json only accepts 'ignore_errors' as a boolean, not '%s'", actual_type);
}
auto val = TransformPythonValue(ignore_errors, LogicalTypeId::BOOLEAN);
options["ignore_errors"] = val;
}
if (!py::none().is(convert_strings_to_integers)) {
if (!py::isinstance<py::bool_>(convert_strings_to_integers)) {
string actual_type = py::str(py::type::of(convert_strings_to_integers));
throw BinderException("read_json only accepts 'convert_strings_to_integers' as a boolean, not '%s'",
actual_type);
}
auto val = TransformPythonValue(convert_strings_to_integers, LogicalTypeId::BOOLEAN);
options["convert_strings_to_integers"] = val;
}
if (!py::none().is(field_appearance_threshold)) {
if (!py::isinstance<py::float_>(field_appearance_threshold)) {
string actual_type = py::str(py::type::of(field_appearance_threshold));
throw BinderException("read_json only accepts 'field_appearance_threshold' as a float, not '%s'",
actual_type);
}
auto val = TransformPythonValue(field_appearance_threshold, LogicalTypeId::DOUBLE);
options["field_appearance_threshold"] = val;
}
if (!py::none().is(map_inference_threshold)) {
if (!py::isinstance<py::int_>(map_inference_threshold)) {
string actual_type = py::str(py::type::of(map_inference_threshold));
throw BinderException("read_json only accepts 'map_inference_threshold' as an integer, not '%s'",
actual_type);
}
auto val = TransformPythonValue(map_inference_threshold, LogicalTypeId::BIGINT);
options["map_inference_threshold"] = val;
}
if (!py::none().is(maximum_sample_files)) {
if (!py::isinstance<py::int_>(maximum_sample_files)) {
string actual_type = py::str(py::type::of(maximum_sample_files));
throw BinderException("read_json only accepts 'maximum_sample_files' as an integer, not '%s'", actual_type);
}
auto val = TransformPythonValue(maximum_sample_files, LogicalTypeId::BIGINT);
options["maximum_sample_files"] = val;
}
bool auto_detect = false;
if (!options.count("columns")) {
options["auto_detect"] = Value::BOOLEAN(true);
auto_detect = true;
}
D_ASSERT(py::gil_check());
py::gil_scoped_release gil;
auto read_json_relation =
make_shared_ptr<ReadJSONRelation>(connection.context, name, std::move(options), auto_detect);
if (read_json_relation == nullptr) {
throw BinderException("read_json can only be used when the JSON extension is (statically) loaded");
}
if (file_like_object_wrapper) {