-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathddbc_bindings.cpp
More file actions
6275 lines (5863 loc) · 303 KB
/
Copy pathddbc_bindings.cpp
File metadata and controls
6275 lines (5863 loc) · 303 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
// INFO|TODO - Note that is file is Windows specific right now. Making it arch
// agnostic will be
// taken up in beta release
#include "ddbc_bindings.h"
#include "connection/connection.h"
#include "connection/connection_pool.h"
#include "logger_bridge.hpp"
#include "performance_counter.hpp"
#include "param_detect.hpp"
#include "py_ref.hpp"
#include "py_type_cache.hpp"
#include "utf_utils.h"
#include <algorithm> // std::min
#include <cctype>
#include <cstdint>
#include <cstring> // For std::memcpy
#include <filesystem>
#include <iostream>
#include <utility> // std::forward
#include <datetime.h> // CPython datetime API (PyDateTime_IMPORT, PyDateTime_GET_*, etc.)
//-------------------------------------------------------------------------------------------------
// Macro definitions
//-------------------------------------------------------------------------------------------------
#ifdef _WIN32
// Constrained DLL search flags (Windows 8+ / Win7 + KB2533623). Defined
// defensively in case the build's SDK headers gate them behind an older
// _WIN32_WINNT than this project targets.
//
// Note: LOAD_LIBRARY_SEARCH_DEFAULT_DIRS is deliberately NOT used. It also
// includes LOAD_LIBRARY_SEARCH_USER_DIRS -- directories any in-process module
// registered via AddDllDirectory/SetDllDirectory -- which is outside the
// trusted set we want. We combine APPLICATION_DIR + SYSTEM32 + DLL_LOAD_DIR
// explicitly instead.
#ifndef LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
#define LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR 0x00000100
#endif
#ifndef LOAD_LIBRARY_SEARCH_APPLICATION_DIR
#define LOAD_LIBRARY_SEARCH_APPLICATION_DIR 0x00000200
#endif
#ifndef LOAD_LIBRARY_SEARCH_SYSTEM32
#define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
#endif
#endif // _WIN32
#ifndef SQL_C_DATE
#define SQL_C_DATE (9)
#endif
#ifndef SQL_C_TIME
#define SQL_C_TIME (10)
#endif
#ifndef SQL_C_TIMESTAMP
#define SQL_C_TIMESTAMP (11)
#endif
// SQL Server-specific variant TIME type code
#define SQL_SS_VARIANT_TIME (16384)
// Space for driver name + up to 8000 characters output by PRINT statements
#define SQL_MAX_MESSAGE_LENGTH_SQLSERVER (10000)
#define STRINGIFY_FOR_CASE(x) \
case x: \
return #x
// Architecture-specific defines
#ifndef ARCHITECTURE
#define ARCHITECTURE "win64" // Default to win64 if not defined during compilation
#endif
#define DAE_CHUNK_SIZE 8192
#define SQL_MAX_LOB_SIZE 8000
// Returns the effective character decoding encoding for SQL_C_CHAR data.
// On Linux/macOS, the ODBC driver always returns UTF-8 for SQL_C_CHAR,
// having already converted from the server's encoding (e.g., CP1252).
// On Windows, the driver returns bytes in the server's native encoding.
inline std::string GetEffectiveCharDecoding(const std::string& userEncoding) {
#if defined(__APPLE__) || defined(__linux__)
(void)userEncoding;
return "utf-8";
#else
return userEncoding;
#endif
}
// Windows-only fix for issue #531: when the user explicitly requests
// SQL_C_CHAR + utf-8 decoding (e.g. setdecoding(SQL_CHAR, "utf-8", SQL_CHAR)),
// the SQL Server ODBC driver on Windows returns VARCHAR data in the server's
// ANSI code page (e.g. CP1252) regardless of the column's actual collation.
// For UTF-8 collation columns or any non-ASCII data, this is lossy ('?'
// substitution) and unrecoverable on the Python side. Internally upgrading
// the fetch to SQL_C_WCHAR triggers the driver's lossless UTF-16 conversion,
// which produces a correct Python Unicode string regardless of column
// collation. On Linux/macOS the SQL_C_CHAR path already returns UTF-8 from
// the driver, so this upgrade is a no-op there.
inline int EffectiveCharCtypeForFetch(int charCtype, const std::string& charEncoding) {
#ifdef _WIN32
if (charCtype == SQL_C_CHAR && charEncoding == "utf-8") {
// Surface the override so users can correlate observed SQL_C_WCHAR
// fetches with their explicit setdecoding(SQL_CHAR, "utf-8", SQL_CHAR)
// call (issue#531). Logged at INFO so it appears in production traces
// without flooding default DEBUG output.
LOG_INFO("EffectiveCharCtypeForFetch: Upgrading SQL_C_CHAR + utf-8 to "
"SQL_C_WCHAR on Windows to avoid lossy ACP conversion ");
return SQL_C_WCHAR;
}
#else
(void)charEncoding;
#endif
return charCtype;
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
// Logging Infrastructure:
// - LOG() macro: All diagnostic/debug logging at DEBUG level (single level)
// - LOG_INFO/WARNING/ERROR: Higher-level messages for production
// Uses printf-style formatting: LOG("Value: %d", x) -- __FILE__/__LINE__
// embedded in macro
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
// Class definitions
//-------------------------------------------------------------------------------------------------
// Struct to hold parameter information for binding. Used by SQLBindParameter.
struct ArrowArrayPrivateData {
std::unique_ptr<uint8_t[]> valid;
std::unique_ptr<uint8_t[]> uint8Val;
std::unique_ptr<int16_t[]> int16Val;
std::unique_ptr<int32_t[]> int32Val;
std::unique_ptr<int64_t[]> int64Val;
std::unique_ptr<double[]> float64Val;
std::unique_ptr<float[]> float32Val;
std::unique_ptr<uint8_t[]> bitVal;
std::unique_ptr<uint64_t[]> varVal;
std::unique_ptr<int32_t[]> dateVal;
std::unique_ptr<int64_t[]> tsMicroVal;
std::unique_ptr<int64_t[]> timeNanoVal;
std::unique_ptr<Int128_t[]> decimalVal;
std::vector<uint8_t> varData;
// first buffer will be the valid bitmap
// second buffer will be one of the value buffers above
// third buffer will be the varData buffer for variable length types
std::array<void*, 3> buffers;
// Points to one of the typed *Val buffers above. Since the buffer pointers
// don't change, this can be set once during batch initialization.
void* ptrValueBuffer;
};
struct ArrowSchemaPrivateData {
std::unique_ptr<char[]> name;
std::unique_ptr<char[]> format;
};
#ifndef ARROW_C_DATA_INTERFACE
#define ARROW_C_DATA_INTERFACE
#define ARROW_FLAG_DICTIONARY_ORDERED 1
#define ARROW_FLAG_NULLABLE 2
#define ARROW_FLAG_MAP_KEYS_SORTED 4
struct ArrowSchema {
// Array type description
const char* format;
const char* name;
const char* metadata;
int64_t flags;
int64_t n_children;
struct ArrowSchema** children;
struct ArrowSchema* dictionary;
// Release callback
void (*release)(struct ArrowSchema*);
// Opaque producer-specific data
// Only our child-arrays will set this, so we can give it the correct type
ArrowSchemaPrivateData* private_data;
};
struct ArrowArray {
// Array data description
int64_t length;
int64_t null_count;
int64_t offset;
int64_t n_buffers;
int64_t n_children;
const void** buffers;
struct ArrowArray** children;
struct ArrowArray* dictionary;
// Release callback
void (*release)(struct ArrowArray*);
// Opaque producer-specific data
// Only our child-arrays will set this, so we can give it the correct type
ArrowArrayPrivateData* private_data;
};
#endif // ARROW_C_DATA_INTERFACE
//-------------------------------------------------------------------------------------------------
// Function pointer initialization
//-------------------------------------------------------------------------------------------------
// Handle APIs
SQLAllocHandleFunc SQLAllocHandle_ptr = nullptr;
SQLSetEnvAttrFunc SQLSetEnvAttr_ptr = nullptr;
SQLSetConnectAttrFunc SQLSetConnectAttr_ptr = nullptr;
SQLSetStmtAttrFunc SQLSetStmtAttr_ptr = nullptr;
SQLGetConnectAttrFunc SQLGetConnectAttr_ptr = nullptr;
// Connection and Execution APIs
SQLDriverConnectFunc SQLDriverConnect_ptr = nullptr;
SQLExecDirectFunc SQLExecDirect_ptr = nullptr;
SQLPrepareFunc SQLPrepare_ptr = nullptr;
SQLBindParameterFunc SQLBindParameter_ptr = nullptr;
SQLExecuteFunc SQLExecute_ptr = nullptr;
SQLRowCountFunc SQLRowCount_ptr = nullptr;
SQLGetStmtAttrFunc SQLGetStmtAttr_ptr = nullptr;
SQLSetDescFieldFunc SQLSetDescField_ptr = nullptr;
// Data retrieval APIs
SQLFetchFunc SQLFetch_ptr = nullptr;
SQLFetchScrollFunc SQLFetchScroll_ptr = nullptr;
SQLGetDataFunc SQLGetData_ptr = nullptr;
SQLNumResultColsFunc SQLNumResultCols_ptr = nullptr;
SQLBindColFunc SQLBindCol_ptr = nullptr;
SQLDescribeColFunc SQLDescribeCol_ptr = nullptr;
SQLMoreResultsFunc SQLMoreResults_ptr = nullptr;
SQLColAttributeFunc SQLColAttribute_ptr = nullptr;
SQLGetTypeInfoFunc SQLGetTypeInfo_ptr = nullptr;
SQLProceduresFunc SQLProcedures_ptr = nullptr;
SQLForeignKeysFunc SQLForeignKeys_ptr = nullptr;
SQLPrimaryKeysFunc SQLPrimaryKeys_ptr = nullptr;
SQLSpecialColumnsFunc SQLSpecialColumns_ptr = nullptr;
SQLStatisticsFunc SQLStatistics_ptr = nullptr;
SQLColumnsFunc SQLColumns_ptr = nullptr;
SQLGetInfoFunc SQLGetInfo_ptr = nullptr;
// Transaction APIs
SQLEndTranFunc SQLEndTran_ptr = nullptr;
// Disconnect/free APIs
SQLFreeHandleFunc SQLFreeHandle_ptr = nullptr;
SQLDisconnectFunc SQLDisconnect_ptr = nullptr;
SQLFreeStmtFunc SQLFreeStmt_ptr = nullptr;
SQLCancelFunc SQLCancel_ptr = nullptr;
// Diagnostic APIs
SQLGetDiagRecFunc SQLGetDiagRec_ptr = nullptr;
// DAE APIs
SQLParamDataFunc SQLParamData_ptr = nullptr;
SQLPutDataFunc SQLPutData_ptr = nullptr;
SQLTablesFunc SQLTables_ptr = nullptr;
SQLDescribeParamFunc SQLDescribeParam_ptr = nullptr;
namespace {
const char* GetSqlCTypeAsString(const SQLSMALLINT cType) {
switch (cType) {
STRINGIFY_FOR_CASE(SQL_C_CHAR);
STRINGIFY_FOR_CASE(SQL_C_WCHAR);
STRINGIFY_FOR_CASE(SQL_C_SSHORT);
STRINGIFY_FOR_CASE(SQL_C_USHORT);
STRINGIFY_FOR_CASE(SQL_C_SHORT);
STRINGIFY_FOR_CASE(SQL_C_SLONG);
STRINGIFY_FOR_CASE(SQL_C_ULONG);
STRINGIFY_FOR_CASE(SQL_C_LONG);
STRINGIFY_FOR_CASE(SQL_C_STINYINT);
STRINGIFY_FOR_CASE(SQL_C_UTINYINT);
STRINGIFY_FOR_CASE(SQL_C_TINYINT);
STRINGIFY_FOR_CASE(SQL_C_SBIGINT);
STRINGIFY_FOR_CASE(SQL_C_UBIGINT);
STRINGIFY_FOR_CASE(SQL_C_FLOAT);
STRINGIFY_FOR_CASE(SQL_C_DOUBLE);
STRINGIFY_FOR_CASE(SQL_C_BIT);
STRINGIFY_FOR_CASE(SQL_C_BINARY);
STRINGIFY_FOR_CASE(SQL_C_TYPE_DATE);
STRINGIFY_FOR_CASE(SQL_C_TYPE_TIME);
STRINGIFY_FOR_CASE(SQL_C_TYPE_TIMESTAMP);
STRINGIFY_FOR_CASE(SQL_C_NUMERIC);
STRINGIFY_FOR_CASE(SQL_C_GUID);
STRINGIFY_FOR_CASE(SQL_C_DEFAULT);
default:
return "Unknown";
}
}
std::string MakeParamMismatchErrorStr(const SQLSMALLINT cType, const int paramIndex) {
std::string errorString = "Parameter's object type does not match "
"parameter's C type. paramIndex - " +
std::to_string(paramIndex) + ", C type - " +
GetSqlCTypeAsString(cType);
return errorString;
}
// This function allocates a buffer of ParamType, stores it as a void* in
// paramBuffers for book-keeping and then returns a ParamType* to the allocated
// memory. ctorArgs are the arguments to ParamType's constructor used while
// creating/allocating ParamType
template <typename ParamType, typename... CtorArgs>
ParamType* AllocateParamBuffer(std::vector<std::shared_ptr<void>>& paramBuffers,
CtorArgs&&... ctorArgs) {
paramBuffers.emplace_back(new ParamType(std::forward<CtorArgs>(ctorArgs)...),
std::default_delete<ParamType>());
return static_cast<ParamType*>(paramBuffers.back().get());
}
template <typename ParamType>
ParamType* AllocateParamBufferArray(std::vector<std::shared_ptr<void>>& paramBuffers,
size_t count) {
std::shared_ptr<ParamType> buffer(new ParamType[count], std::default_delete<ParamType[]>());
ParamType* raw = buffer.get();
paramBuffers.push_back(buffer);
return raw;
}
std::string DescribeChar(unsigned char ch) {
if (ch >= 32 && ch <= 126) {
return std::string("'") + static_cast<char>(ch) + "'";
} else {
char buffer[16];
snprintf(buffer, sizeof(buffer), "U+%04X", ch);
return std::string(buffer);
}
}
template<typename PutDataFn>
// The callable hides whether the caller wraps SQLPutData with GIL management; chunk sizing stays shared.
static SQLRETURN stream_dae_chunks(const void* data, size_t total_bytes, PutDataFn put_data_fn) {
const char* bytes = static_cast<const char*>(data);
for (size_t offset = 0; offset < total_bytes; offset += DAE_CHUNK_SIZE) {
size_t len = std::min(static_cast<size_t>(DAE_CHUNK_SIZE), total_bytes - offset);
SQLRETURN rc = put_data_fn(
static_cast<SQLPOINTER>(const_cast<char*>(bytes + offset)), static_cast<SQLLEN>(len));
if (!SQL_SUCCEEDED(rc)) return rc;
}
return SQL_SUCCESS;
}
// GH-610: Resolve SQL type for a NULL parameter using per-handle cache.
// On cache miss, calls SQLDescribeParam and stores the result.
static DescribedParamInfo ResolveNullParamType(SqlHandle& handle, SQLHANDLE hStmt, int paramIndex) {
// Check per-handle cache. ODBC mandates one handle per thread, so no
// mutex is needed. Violating this contract causes undefined behavior.
auto it = handle.describeCache.find(paramIndex);
if (it != handle.describeCache.end()) {
LOG("ResolveNullParamType: Cache HIT for hStmt=%p param[%d] "
"-> sqlType=%d",
(void*)hStmt, paramIndex, it->second.sqlType);
return it->second;
}
// Cache miss — call SQLDescribeParam
SQLSMALLINT type, digits, nullable;
SQLULEN size;
LOG("ResolveNullParamType: Cache MISS for hStmt=%p param[%d], calling "
"SQLDescribeParam", (void*)hStmt, paramIndex);
// SQLDescribeParam may issue a server round-trip
// (sp_describe_undeclared_parameters). Release the GIL around it so
// in-process Python TCP forwarders can run (issue #565 family).
RETCODE rc;
{
py::gil_scoped_release release;
rc = SQLDescribeParam_ptr(
hStmt, static_cast<SQLUSMALLINT>(paramIndex + 1),
&type, &size, &digits, &nullable);
}
DescribedParamInfo info;
if (SQL_SUCCEEDED(rc)) {
info = {type, size, digits};
LOG("ResolveNullParamType: SQLDescribeParam succeeded for param[%d] "
"-> sqlType=%d, columnSize=%lu, decimalDigits=%d",
paramIndex, type, (unsigned long)size, digits);
} else {
// SQLDescribeParam failed — typically happens with temp tables (#table),
// table variables, or complex CTEs where the driver cannot determine
// parameter metadata. Fall back to SQL_VARCHAR which works for most
// column types but will fail for BINARY/VARBINARY columns due to SQL
// Server's implicit conversion rules.
//
// Workaround: cursor.setinputsizes() to explicitly specify types.
// from mssql_python.constants import ConstantsDDBC
// cursor.setinputsizes([(ConstantsDDBC.SQL_INTEGER.value, 10, 0),
// (ConstantsDDBC.SQL_VARBINARY.value, 0, 0)])
// cursor.execute("INSERT INTO #t (id, data) VALUES (?, ?)", [1, None])
info = {SQL_VARCHAR, 1, 0};
LOG_WARNING("ResolveNullParamType: SQLDescribeParam failed for "
"param[%d] (rc=%d), falling back to SQL_VARCHAR",
paramIndex, rc);
}
// Cache both successful and fallback results. For fallbacks, this avoids
// repeated SQLDescribeParam network calls on statement reuse. Note: on the
// same_sql path clearDescribeCache() is NOT called, so a transient describe
// failure is pinned as SQL_VARCHAR for the life of the prepared statement.
// This is intentional — retrying a failing describe on every execute would
// add latency with no benefit (temp-table metadata won't become resolvable
// mid-connection). The cache IS cleared on SQLPrepare (usePrepare path).
handle.describeCache[paramIndex] = info;
return info;
}
// GH-627: Resolve unknown NULL SQL types before any SQLBindParameter calls.
// Some drivers remap parameter ordinals during describe when parameters have
// already been bound, so interleaving describe+bind can fail for binary NULLs.
// When `params` is provided (execute path), an additional py::none check is
// performed; for executemany (array path), SQL_C_DEFAULT already guarantees
// all values in that column are NULL, so no Python-level check is needed.
static void PreResolveUnknownNullTypes(SqlHandle& handle, SQLHANDLE hStmt,
std::vector<ParamInfo>& paramInfos,
const py::list* params = nullptr) {
if (paramInfos.empty())
return;
for (size_t paramIndex = 0; paramIndex < paramInfos.size(); ++paramIndex) {
ParamInfo& paramInfo = paramInfos[paramIndex];
if (paramInfo.paramCType != SQL_C_DEFAULT || paramInfo.paramSQLType != SQL_UNKNOWN_TYPE) {
continue;
}
// For execute(), verify the actual value is None (mixed columns possible).
if (params && paramIndex < params->size() &&
!py::isinstance<py::none>((*params)[paramIndex])) {
continue;
}
auto resolved = ResolveNullParamType(handle, hStmt, static_cast<int>(paramIndex));
paramInfo.paramSQLType = resolved.sqlType;
paramInfo.columnSize = resolved.columnSize;
paramInfo.decimalDigits = resolved.decimalDigits;
}
}
// Given a list of parameters and their ParamInfo, calls SQLBindParameter on
// each of them with appropriate arguments
SQLRETURN BindParameters(SqlHandle& handle, SQLHANDLE hStmt, const py::list& params,
std::vector<ParamInfo>& paramInfos,
std::vector<std::shared_ptr<void>>& paramBuffers,
const std::string& charEncoding = "utf-8") {
PERF_TIMER("BindParameters");
LOG("BindParameters: Starting parameter binding for statement handle %p "
"with %zu parameters",
(void*)hStmt, params.size());
// GH-627: resolve unknown NULL param SQL types before binding any param.
PreResolveUnknownNullTypes(handle, hStmt, paramInfos, ¶ms);
for (int paramIndex = 0; paramIndex < params.size(); paramIndex++) {
const auto& param = params[paramIndex];
ParamInfo& paramInfo = paramInfos[paramIndex];
LOG("BindParameters: Processing param[%d] - C_Type=%d, SQL_Type=%d, "
"ColumnSize=%lu, DecimalDigits=%d, InputOutputType=%d",
paramIndex, paramInfo.paramCType, paramInfo.paramSQLType,
(unsigned long)paramInfo.columnSize, paramInfo.decimalDigits,
paramInfo.inputOutputType);
void* dataPtr = nullptr;
SQLLEN bufferLength = 0;
SQLLEN* strLenOrIndPtr = nullptr;
// TODO: Add more data types like money, guid, interval, TVPs etc.
switch (paramInfo.paramCType) {
case SQL_C_CHAR: {
if (!py::isinstance<py::str>(param) && !py::isinstance<py::bytearray>(param) &&
!py::isinstance<py::bytes>(param)) {
ThrowStdException(MakeParamMismatchErrorStr(paramInfo.paramCType, paramIndex));
}
if (paramInfo.isDAE) {
LOG("BindParameters: param[%d] SQL_C_CHAR - Using DAE "
"(Data-At-Execution) for large string streaming",
paramIndex);
dataPtr =
const_cast<void*>(reinterpret_cast<const void*>(¶mInfos[paramIndex]));
strLenOrIndPtr = AllocateParamBuffer<SQLLEN>(paramBuffers);
*strLenOrIndPtr = SQL_LEN_DATA_AT_EXEC(0);
bufferLength = 0;
} else {
// Use Python's codec system to encode the string with specified encoding
std::string encodedStr;
if (py::isinstance<py::str>(param)) {
// Encode Unicode string using the specified encoding
try {
py::object encoded = param.attr("encode")(charEncoding, "strict");
encodedStr = encoded.cast<std::string>();
LOG("BindParameters: param[%d] SQL_C_CHAR - Encoded with '%s', "
"size=%zu bytes",
paramIndex, charEncoding.c_str(), encodedStr.size());
} catch (const py::error_already_set& e) {
LOG_ERROR("BindParameters: param[%d] SQL_C_CHAR - Failed to encode "
"with '%s': %s",
paramIndex, charEncoding.c_str(), e.what());
throw std::runtime_error(std::string("Failed to encode parameter ") +
std::to_string(paramIndex) +
" with encoding '" + charEncoding +
"': " + e.what());
}
} else {
// bytes/bytearray - use as-is (already encoded)
if (py::isinstance<py::bytes>(param)) {
encodedStr = param.cast<std::string>();
} else {
// bytearray
encodedStr = std::string(
reinterpret_cast<const char*>(PyByteArray_AsString(param.ptr())),
PyByteArray_Size(param.ptr()));
}
LOG("BindParameters: param[%d] SQL_C_CHAR - Using raw bytes, size=%zu",
paramIndex, encodedStr.size());
}
std::string* strParam =
AllocateParamBuffer<std::string>(paramBuffers, encodedStr);
dataPtr = const_cast<void*>(static_cast<const void*>(strParam->data()));
bufferLength = strParam->size();
strLenOrIndPtr = AllocateParamBuffer<SQLLEN>(paramBuffers);
// Use explicit byte length instead of SQL_NTS so embedded NUL chars
// aren't treated as string terminators (e.g., "hello\x00world").
*strLenOrIndPtr = static_cast<SQLLEN>(strParam->size());
}
break;
}
case SQL_C_BINARY: {
if (!py::isinstance<py::str>(param) && !py::isinstance<py::bytearray>(param) &&
!py::isinstance<py::bytes>(param)) {
ThrowStdException(MakeParamMismatchErrorStr(paramInfo.paramCType, paramIndex));
}
if (paramInfo.isDAE) {
// Deferred execution for VARBINARY(MAX)
LOG("BindParameters: param[%d] SQL_C_BINARY - Using DAE "
"for VARBINARY(MAX) streaming",
paramIndex);
dataPtr =
const_cast<void*>(reinterpret_cast<const void*>(¶mInfos[paramIndex]));
strLenOrIndPtr = AllocateParamBuffer<SQLLEN>(paramBuffers);
*strLenOrIndPtr = SQL_LEN_DATA_AT_EXEC(0);
bufferLength = 0;
} else {
// small binary
std::string binData;
if (py::isinstance<py::bytes>(param)) {
binData = param.cast<std::string>();
} else {
// bytearray
binData = std::string(
reinterpret_cast<const char*>(PyByteArray_AsString(param.ptr())),
PyByteArray_Size(param.ptr()));
}
std::string* binBuffer =
AllocateParamBuffer<std::string>(paramBuffers, binData);
dataPtr = const_cast<void*>(static_cast<const void*>(binBuffer->data()));
bufferLength = static_cast<SQLLEN>(binBuffer->size());
strLenOrIndPtr = AllocateParamBuffer<SQLLEN>(paramBuffers);
*strLenOrIndPtr = bufferLength;
}
break;
}
case SQL_C_WCHAR: {
if (!py::isinstance<py::str>(param) && !py::isinstance<py::bytearray>(param) &&
!py::isinstance<py::bytes>(param)) {
ThrowStdException(MakeParamMismatchErrorStr(paramInfo.paramCType, paramIndex));
}
if (paramInfo.isDAE) {
// deferred execution
LOG("BindParameters: param[%d] SQL_C_WCHAR - Using DAE for "
"NVARCHAR(MAX) streaming",
paramIndex);
dataPtr =
const_cast<void*>(reinterpret_cast<const void*>(¶mInfos[paramIndex]));
strLenOrIndPtr = AllocateParamBuffer<SQLLEN>(paramBuffers);
*strLenOrIndPtr = SQL_LEN_DATA_AT_EXEC(0);
bufferLength = 0;
} else {
// Normal small-string case
std::u16string* sqlwcharBuffer = AllocateParamBuffer<std::u16string>(
paramBuffers, param.cast<std::u16string>());
LOG("BindParameters: param[%d] SQL_C_WCHAR - String "
"length=%zu characters, buffer=%zu bytes",
paramIndex, sqlwcharBuffer->size(),
sqlwcharBuffer->size() * sizeof(SQLWCHAR));
dataPtr = sqlwcharBuffer->data();
bufferLength = sqlwcharBuffer->size() * sizeof(SQLWCHAR);
strLenOrIndPtr = AllocateParamBuffer<SQLLEN>(paramBuffers);
// Use explicit byte length instead of SQL_NTS so embedded NUL chars
// aren't treated as string terminators.
*strLenOrIndPtr = static_cast<SQLLEN>(sqlwcharBuffer->size() * sizeof(SQLWCHAR));
}
break;
}
case SQL_C_BIT: {
if (!py::isinstance<py::bool_>(param)) {
ThrowStdException(MakeParamMismatchErrorStr(paramInfo.paramCType, paramIndex));
}
dataPtr =
static_cast<void*>(AllocateParamBuffer<bool>(paramBuffers, param.cast<bool>()));
break;
}
case SQL_C_DEFAULT: {
if (!py::isinstance<py::none>(param)) {
ThrowStdException(MakeParamMismatchErrorStr(paramInfo.paramCType, paramIndex));
}
dataPtr = nullptr; // GH-627: type resolved by PreResolveUnknownNullTypes.
strLenOrIndPtr = AllocateParamBuffer<SQLLEN>(paramBuffers);
*strLenOrIndPtr = SQL_NULL_DATA;
bufferLength = 0;
break;
}
case SQL_C_STINYINT:
case SQL_C_TINYINT:
case SQL_C_SSHORT:
case SQL_C_SHORT: {
if (!py::isinstance<py::int_>(param)) {
ThrowStdException(MakeParamMismatchErrorStr(paramInfo.paramCType, paramIndex));
}
int value = param.cast<int>();
// Range validation for signed 16-bit integer
if (value < std::numeric_limits<short>::min() ||
value > std::numeric_limits<short>::max()) {
ThrowStdException("Signed short integer parameter out of "
"range at paramIndex " +
std::to_string(paramIndex));
}
dataPtr =
static_cast<void*>(AllocateParamBuffer<int>(paramBuffers, param.cast<int>()));
break;
}
case SQL_C_UTINYINT:
case SQL_C_USHORT: {
if (!py::isinstance<py::int_>(param)) {
ThrowStdException(MakeParamMismatchErrorStr(paramInfo.paramCType, paramIndex));
}
unsigned int value = param.cast<unsigned int>();
if (value > std::numeric_limits<unsigned short>::max()) {
ThrowStdException("Unsigned short integer parameter out of "
"range at paramIndex " +
std::to_string(paramIndex));
}
dataPtr = static_cast<void*>(
AllocateParamBuffer<unsigned int>(paramBuffers, param.cast<unsigned int>()));
break;
}
case SQL_C_SBIGINT:
case SQL_C_SLONG:
case SQL_C_LONG: {
if (!py::isinstance<py::int_>(param)) {
ThrowStdException(MakeParamMismatchErrorStr(paramInfo.paramCType, paramIndex));
}
// Both detection paths (DetectParamTypes / _map_sql_type) reject out-of-int64
// ints before binding, so those callers only reach here with bindable values.
// A setinputsizes() override that forces SQL_C_SBIGINT on an out-of-range int
// skips detection; that value fails the cast below, same as before this change.
dataPtr = static_cast<void*>(
AllocateParamBuffer<int64_t>(paramBuffers, param.cast<int64_t>()));
break;
}
case SQL_C_UBIGINT:
case SQL_C_ULONG: {
if (!py::isinstance<py::int_>(param)) {
ThrowStdException(MakeParamMismatchErrorStr(paramInfo.paramCType, paramIndex));
}
dataPtr = static_cast<void*>(
AllocateParamBuffer<uint64_t>(paramBuffers, param.cast<uint64_t>()));
break;
}
case SQL_C_FLOAT: {
if (!py::isinstance<py::float_>(param)) {
ThrowStdException(MakeParamMismatchErrorStr(paramInfo.paramCType, paramIndex));
}
dataPtr = static_cast<void*>(
AllocateParamBuffer<float>(paramBuffers, param.cast<float>()));
break;
}
case SQL_C_DOUBLE: {
if (!py::isinstance<py::float_>(param)) {
ThrowStdException(MakeParamMismatchErrorStr(paramInfo.paramCType, paramIndex));
}
dataPtr = static_cast<void*>(
AllocateParamBuffer<double>(paramBuffers, param.cast<double>()));
break;
}
case SQL_C_TYPE_DATE: {
py::object dateType = PyTypeCache::get_date_class_obj();
if (!py::isinstance(param, dateType)) {
ThrowStdException(MakeParamMismatchErrorStr(paramInfo.paramCType, paramIndex));
}
int year = param.attr("year").cast<int>();
if (year < 1753 || year > 9999) {
ThrowStdException("Date out of range for SQL Server "
"(1753-9999) at paramIndex " +
std::to_string(paramIndex));
}
// TODO: can be moved to python by registering SQL_DATE_STRUCT
// in pybind
SQL_DATE_STRUCT* sqlDatePtr = AllocateParamBuffer<SQL_DATE_STRUCT>(paramBuffers);
sqlDatePtr->year = static_cast<SQLSMALLINT>(param.attr("year").cast<int>());
sqlDatePtr->month = static_cast<SQLUSMALLINT>(param.attr("month").cast<int>());
sqlDatePtr->day = static_cast<SQLUSMALLINT>(param.attr("day").cast<int>());
dataPtr = static_cast<void*>(sqlDatePtr);
break;
}
case SQL_C_TYPE_TIME: {
py::object timeType = PyTypeCache::get_time_class_obj();
if (!py::isinstance(param, timeType)) {
ThrowStdException(MakeParamMismatchErrorStr(paramInfo.paramCType, paramIndex));
}
// TODO: can be moved to python by registering SQL_TIME_STRUCT
// in pybind
SQL_TIME_STRUCT* sqlTimePtr = AllocateParamBuffer<SQL_TIME_STRUCT>(paramBuffers);
sqlTimePtr->hour = static_cast<SQLUSMALLINT>(param.attr("hour").cast<int>());
sqlTimePtr->minute = static_cast<SQLUSMALLINT>(param.attr("minute").cast<int>());
sqlTimePtr->second = static_cast<SQLUSMALLINT>(param.attr("second").cast<int>());
dataPtr = static_cast<void*>(sqlTimePtr);
break;
}
case SQL_C_SS_TIMESTAMPOFFSET: {
py::object datetimeType = PyTypeCache::get_datetime_class_obj();
if (!py::isinstance(param, datetimeType)) {
ThrowStdException(MakeParamMismatchErrorStr(paramInfo.paramCType, paramIndex));
}
// Checking if the object has a timezone
py::object tzinfo = param.attr("tzinfo");
if (tzinfo.is_none()) {
ThrowStdException("Datetime object must have tzinfo for "
"SQL_C_SS_TIMESTAMPOFFSET at paramIndex " +
std::to_string(paramIndex));
}
DateTimeOffset* dtoPtr = AllocateParamBuffer<DateTimeOffset>(paramBuffers);
dtoPtr->year = static_cast<SQLSMALLINT>(param.attr("year").cast<int>());
dtoPtr->month = static_cast<SQLUSMALLINT>(param.attr("month").cast<int>());
dtoPtr->day = static_cast<SQLUSMALLINT>(param.attr("day").cast<int>());
dtoPtr->hour = static_cast<SQLUSMALLINT>(param.attr("hour").cast<int>());
dtoPtr->minute = static_cast<SQLUSMALLINT>(param.attr("minute").cast<int>());
dtoPtr->second = static_cast<SQLUSMALLINT>(param.attr("second").cast<int>());
// SQL server supports in ns, but python datetime supports in µs
dtoPtr->fraction =
static_cast<SQLUINTEGER>(param.attr("microsecond").cast<int>() * 1000);
py::object utcoffset = tzinfo.attr("utcoffset")(param);
if (utcoffset.is_none()) {
ThrowStdException("Datetime object's tzinfo.utcoffset() "
"returned None at paramIndex " +
std::to_string(paramIndex));
}
int total_seconds =
static_cast<int>(utcoffset.attr("total_seconds")().cast<double>());
const int MAX_OFFSET = 14 * 3600;
const int MIN_OFFSET = -14 * 3600;
if (total_seconds > MAX_OFFSET || total_seconds < MIN_OFFSET) {
ThrowStdException("Datetimeoffset tz offset out of SQL Server range "
"(-14h to +14h) at paramIndex " +
std::to_string(paramIndex));
}
std::div_t div_result = std::div(total_seconds, 3600);
dtoPtr->timezone_hour = static_cast<SQLSMALLINT>(div_result.quot);
dtoPtr->timezone_minute = static_cast<SQLSMALLINT>(div(div_result.rem, 60).quot);
dataPtr = static_cast<void*>(dtoPtr);
bufferLength = sizeof(DateTimeOffset);
strLenOrIndPtr = AllocateParamBuffer<SQLLEN>(paramBuffers);
*strLenOrIndPtr = bufferLength;
break;
}
case SQL_C_TYPE_TIMESTAMP: {
py::object datetimeType = PyTypeCache::get_datetime_class_obj();
if (!py::isinstance(param, datetimeType)) {
ThrowStdException(MakeParamMismatchErrorStr(paramInfo.paramCType, paramIndex));
}
SQL_TIMESTAMP_STRUCT* sqlTimestampPtr =
AllocateParamBuffer<SQL_TIMESTAMP_STRUCT>(paramBuffers);
sqlTimestampPtr->year = static_cast<SQLSMALLINT>(param.attr("year").cast<int>());
sqlTimestampPtr->month = static_cast<SQLUSMALLINT>(param.attr("month").cast<int>());
sqlTimestampPtr->day = static_cast<SQLUSMALLINT>(param.attr("day").cast<int>());
sqlTimestampPtr->hour = static_cast<SQLUSMALLINT>(param.attr("hour").cast<int>());
sqlTimestampPtr->minute =
static_cast<SQLUSMALLINT>(param.attr("minute").cast<int>());
sqlTimestampPtr->second =
static_cast<SQLUSMALLINT>(param.attr("second").cast<int>());
// SQL server supports in ns, but python datetime supports in µs
sqlTimestampPtr->fraction = static_cast<SQLUINTEGER>(
param.attr("microsecond").cast<int>() * 1000); // Convert µs to ns
dataPtr = static_cast<void*>(sqlTimestampPtr);
break;
}
case SQL_C_NUMERIC: {
if (!py::isinstance<NumericData>(param)) {
ThrowStdException(MakeParamMismatchErrorStr(paramInfo.paramCType, paramIndex));
}
NumericData decimalParam = param.cast<NumericData>();
LOG("BindParameters: param[%d] SQL_C_NUMERIC - precision=%d, "
"scale=%d, sign=%d, value_bytes=%zu",
paramIndex, decimalParam.precision, decimalParam.scale, decimalParam.sign,
decimalParam.val.size());
SQL_NUMERIC_STRUCT* decimalPtr =
AllocateParamBuffer<SQL_NUMERIC_STRUCT>(paramBuffers);
decimalPtr->precision = decimalParam.precision;
decimalPtr->scale = decimalParam.scale;
decimalPtr->sign = decimalParam.sign;
// Convert the integer decimalParam.val to char array
std::memset(static_cast<void*>(decimalPtr->val), 0, sizeof(decimalPtr->val));
size_t copyLen = std::min(decimalParam.val.size(), sizeof(decimalPtr->val));
if (copyLen > 0) {
std::memcpy(decimalPtr->val, decimalParam.val.data(), copyLen);
}
dataPtr = static_cast<void*>(decimalPtr);
break;
}
case SQL_C_GUID: {
if (!py::isinstance<py::bytes>(param)) {
ThrowStdException(MakeParamMismatchErrorStr(paramInfo.paramCType, paramIndex));
}
py::bytes uuid_bytes = param.cast<py::bytes>();
const unsigned char* uuid_data =
reinterpret_cast<const unsigned char*>(PyBytes_AS_STRING(uuid_bytes.ptr()));
if (PyBytes_GET_SIZE(uuid_bytes.ptr()) != 16) {
LOG("BindParameters: param[%d] SQL_C_GUID - Invalid UUID "
"length: expected 16 bytes, got %ld bytes",
paramIndex, PyBytes_GET_SIZE(uuid_bytes.ptr()));
ThrowStdException("UUID binary data must be exactly 16 bytes long.");
}
SQLGUID* guid_data_ptr = AllocateParamBuffer<SQLGUID>(paramBuffers);
guid_data_ptr->Data1 = (static_cast<uint32_t>(uuid_data[3]) << 24) |
(static_cast<uint32_t>(uuid_data[2]) << 16) |
(static_cast<uint32_t>(uuid_data[1]) << 8) |
(static_cast<uint32_t>(uuid_data[0]));
guid_data_ptr->Data2 = (static_cast<uint16_t>(uuid_data[5]) << 8) |
(static_cast<uint16_t>(uuid_data[4]));
guid_data_ptr->Data3 = (static_cast<uint16_t>(uuid_data[7]) << 8) |
(static_cast<uint16_t>(uuid_data[6]));
std::memcpy(guid_data_ptr->Data4, &uuid_data[8], 8);
dataPtr = static_cast<void*>(guid_data_ptr);
bufferLength = sizeof(SQLGUID);
strLenOrIndPtr = AllocateParamBuffer<SQLLEN>(paramBuffers);
*strLenOrIndPtr = sizeof(SQLGUID);
break;
}
default: {
std::ostringstream errorString;
errorString << "Unsupported parameter type - " << paramInfo.paramCType
<< " for parameter - " << paramIndex;
ThrowStdException(errorString.str());
}
}
assert(SQLBindParameter_ptr && SQLGetStmtAttr_ptr && SQLSetDescField_ptr);
RETCODE rc;
{
PERF_TIMER("BindParameters::SQLBindParameter_call");
rc = SQLBindParameter_ptr(
hStmt, static_cast<SQLUSMALLINT>(paramIndex + 1), /* 1-based indexing */
static_cast<SQLUSMALLINT>(paramInfo.inputOutputType),
static_cast<SQLSMALLINT>(paramInfo.paramCType),
static_cast<SQLSMALLINT>(paramInfo.paramSQLType), paramInfo.columnSize,
paramInfo.decimalDigits, dataPtr, bufferLength, strLenOrIndPtr);
}
if (!SQL_SUCCEEDED(rc)) {
LOG("BindParameters: SQLBindParameter failed for param[%d] - "
"SQLRETURN=%d, C_Type=%d, SQL_Type=%d",
paramIndex, rc, paramInfo.paramCType, paramInfo.paramSQLType);
return rc;
}
// Special handling for Numeric type -
// https://learn.microsoft.com/en-us/sql/odbc/reference/appendixes/retrieve-numeric-data-sql-numeric-struct-kb222831?view=sql-server-ver16#sql_c_numeric-overview
if (paramInfo.paramCType == SQL_C_NUMERIC) {
// The APD record number is the 1-based parameter position, matching the
// SQLBindParameter call above. It was previously hardcoded to 1, so a
// SQL_C_NUMERIC parameter in any position other than the first had its
// precision/scale/data pointer written onto record 1 instead of its own.
// The driver then read the numeric struct with the wrong descriptor and
// raised "Numeric value out of range" (GH-740).
const SQLSMALLINT descRecNum = static_cast<SQLSMALLINT>(paramIndex + 1);
SQLHDESC hDesc = nullptr;
rc = SQLGetStmtAttr_ptr(hStmt, SQL_ATTR_APP_PARAM_DESC, &hDesc, 0, NULL);
if (!SQL_SUCCEEDED(rc)) {
LOG("BindParameters: SQLGetStmtAttr(SQL_ATTR_APP_PARAM_DESC) "
"failed for param[%d] - SQLRETURN=%d",
paramIndex, rc);
return rc;
}
rc = SQLSetDescField_ptr(hDesc, descRecNum, SQL_DESC_TYPE,
(SQLPOINTER)SQL_C_NUMERIC, 0);
if (!SQL_SUCCEEDED(rc)) {
LOG("BindParameters: SQLSetDescField(SQL_DESC_TYPE) failed for "
"param[%d] - SQLRETURN=%d",
paramIndex, rc);
return rc;
}
SQL_NUMERIC_STRUCT* numericPtr = reinterpret_cast<SQL_NUMERIC_STRUCT*>(dataPtr);
rc = SQLSetDescField_ptr(
hDesc, descRecNum, SQL_DESC_PRECISION,
reinterpret_cast<SQLPOINTER>(static_cast<uintptr_t>(numericPtr->precision)), 0);
if (!SQL_SUCCEEDED(rc)) {
LOG("BindParameters: SQLSetDescField(SQL_DESC_PRECISION) "
"failed for param[%d] - SQLRETURN=%d",
paramIndex, rc);
return rc;
}
rc = SQLSetDescField_ptr(
hDesc, descRecNum, SQL_DESC_SCALE,
reinterpret_cast<SQLPOINTER>(static_cast<intptr_t>(numericPtr->scale)), 0);
if (!SQL_SUCCEEDED(rc)) {
LOG("BindParameters: SQLSetDescField(SQL_DESC_SCALE) failed "
"for param[%d] - SQLRETURN=%d",
paramIndex, rc);
return rc;
}
rc = SQLSetDescField_ptr(hDesc, descRecNum, SQL_DESC_DATA_PTR,
reinterpret_cast<SQLPOINTER>(numericPtr), 0);
if (!SQL_SUCCEEDED(rc)) {
LOG("BindParameters: SQLSetDescField(SQL_DESC_DATA_PTR) failed "
"for param[%d] - SQLRETURN=%d",
paramIndex, rc);
return rc;
}
}
}
LOG("BindParameters: Completed parameter binding for statement handle %p - "
"%zu parameters bound successfully",
(void*)hStmt, params.size());
return SQL_SUCCESS;
}
// This is temporary hack to avoid crash when SQLDescribeCol returns 0 as
// columnSize for NVARCHAR(MAX) & similar types. Variable length data needs more
// nuanced handling.
// TODO: Fix this in beta
// This function sets the buffer allocated to fetch NVARCHAR(MAX) & similar
// types to 4096 chars. So we'll retrieve data upto 4096. Anything greater then
// that will throw error
void HandleZeroColumnSizeAtFetch(SQLULEN& columnSize) {
if (columnSize == 0) {
columnSize = 4096;
}
}
} // namespace
// Helper function to check if Python is shutting down or finalizing
// This centralizes the shutdown detection logic to avoid code duplication
//
// IMPORTANT: must not blindly acquire the GIL. The previous implementation
// used py::gil_scoped_acquire + sys._is_finalizing(), which calls
// PyGILState_Ensure() under the hood. When invoked from a thread CPython
// doesn't already know about (e.g. a foreign/background thread dropping the
// last shared_ptr<SqlHandle> reference) while the interpreter is finalizing,
// PyGILState_Ensure() can fail to register thread-local state and crash with
// "Fatal Python error: gilstate_tss_set: failed to set current tstate (TSS)"
// - i.e. the very safety check meant to prevent a shutdown-time crash can
// itself cause one.
static bool is_python_finalizing() {
if (Py_IsInitialized() == 0) {
return true; // Python is already shut down
}
#if PY_VERSION_HEX >= 0x030D0000
// Py_IsFinalizing() is a public, thread-safe, GIL-free CPython API
// (stable since Python 3.13) built exactly for this purpose.
return Py_IsFinalizing() != 0;
#else
// Older Python versions don't expose the public Py_IsFinalizing(), but the
// exported CPython 3.7+ call it wraps, _Py_IsFinalizing(), is equally
// GIL-free and thread-safe (pybind11 itself uses it for this purpose). Use
// it so the check is accurate: a foreign/GIL-free thread dropping the last
// handle reference during NORMAL operation reports "not finalizing" and the
// handle is actually freed, instead of a PyGILState_Check() proxy that would
// treat every GIL-free caller as shutdown and silently leak the handle.
return _Py_IsFinalizing() != 0;
#endif
}
// TODO: Add more nuanced exception classes
void ThrowStdException(const std::string& message) {
throw std::runtime_error(message);
}
std::string GetLastErrorMessage();
// Resolve the base directory that contains the ODBC driver `libs/` tree.
//
// Post-split, the driver binaries ship in the standalone `mssql_python_odbc`
// package (a pure-data sibling with no native extension). We import it and use
// its directory as the base that `GetDriverPathCpp` (and the Windows
// `mssql-auth.dll` lookup) append `libs` to.