-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathddbc_bindings.cpp
More file actions
4472 lines (4176 loc) · 212 KB
/
ddbc_bindings.cpp
File metadata and controls
4472 lines (4176 loc) · 212 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 <cstdint>
#include <cstring> // For std::memcpy
#include <filesystem>
#include <iomanip> // std::setw, std::setfill
#include <iostream>
#include <utility> // std::forward
//-------------------------------------------------------------------------------------------------
// Macro definitions
//-------------------------------------------------------------------------------------------------
// This constant is not exposed via sql.h, hence define it here
#define SQL_SS_TIME2 (-154)
#define SQL_SS_TIMESTAMPOFFSET (-155)
#define SQL_C_SS_TIMESTAMPOFFSET (0x4001)
#define MAX_DIGITS_IN_NUMERIC 64
#define SQL_MAX_NUMERIC_LEN 16
#define SQL_SS_XML (-152)
#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
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
// 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
//-------------------------------------------------------------------------------------------------
namespace PythonObjectCache {
static py::object datetime_class;
static py::object date_class;
static py::object time_class;
static py::object decimal_class;
static py::object uuid_class;
static bool cache_initialized = false;
void initialize() {
if (!cache_initialized) {
auto datetime_module = py::module_::import("datetime");
datetime_class = datetime_module.attr("datetime");
date_class = datetime_module.attr("date");
time_class = datetime_module.attr("time");
auto decimal_module = py::module_::import("decimal");
decimal_class = decimal_module.attr("Decimal");
auto uuid_module = py::module_::import("uuid");
uuid_class = uuid_module.attr("UUID");
cache_initialized = true;
}
}
py::object get_datetime_class() {
if (cache_initialized && datetime_class) {
return datetime_class;
}
return py::module_::import("datetime").attr("datetime");
}
py::object get_date_class() {
if (cache_initialized && date_class) {
return date_class;
}
return py::module_::import("datetime").attr("date");
}
py::object get_time_class() {
if (cache_initialized && time_class) {
return time_class;
}
return py::module_::import("datetime").attr("time");
}
py::object get_decimal_class() {
if (cache_initialized && decimal_class) {
return decimal_class;
}
return py::module_::import("decimal").attr("Decimal");
}
py::object get_uuid_class() {
if (cache_initialized && uuid_class) {
return uuid_class;
}
return py::module_::import("uuid").attr("UUID");
}
} // namespace PythonObjectCache
//-------------------------------------------------------------------------------------------------
// Class definitions
//-------------------------------------------------------------------------------------------------
// Struct to hold parameter information for binding. Used by SQLBindParameter.
// This struct is shared between C++ & Python code.
// Suppress -Wattributes warning for ParamInfo struct
// The warning is triggered because pybind11 handles visibility attributes automatically,
// and having additional attributes on the struct can cause conflicts on Linux with GCC
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wattributes"
#endif
struct ParamInfo {
SQLSMALLINT inputOutputType;
SQLSMALLINT paramCType;
SQLSMALLINT paramSQLType;
SQLULEN columnSize;
SQLSMALLINT decimalDigits;
SQLLEN strLenOrInd = 0; // Required for DAE
bool isDAE = false; // Indicates if we need to stream
py::object dataPtr;
};
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
// Mirrors the SQL_NUMERIC_STRUCT. But redefined to replace val char array
// with std::string, because pybind doesn't allow binding char array.
// This struct is shared between C++ & Python code.
struct NumericData {
SQLCHAR precision;
SQLSCHAR scale;
SQLCHAR sign; // 1=pos, 0=neg
std::string val; // 123.45 -> 12345
NumericData() : precision(0), scale(0), sign(0), val(SQL_MAX_NUMERIC_LEN, '\0') {}
NumericData(SQLCHAR precision, SQLSCHAR scale, SQLCHAR sign, const std::string& valueBytes)
: precision(precision), scale(scale), sign(sign), val(SQL_MAX_NUMERIC_LEN, '\0') {
if (valueBytes.size() > SQL_MAX_NUMERIC_LEN) {
throw std::runtime_error(
"NumericData valueBytes size exceeds SQL_MAX_NUMERIC_LEN (16)");
}
// Copy binary data to buffer, remaining bytes stay zero-padded
std::memcpy(&val[0], valueBytes.data(), valueBytes.size());
}
};
//-------------------------------------------------------------------------------------------------
// 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;
// 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);
}
}
// Given a list of parameters and their ParamInfo, calls SQLBindParameter on
// each of them with appropriate arguments
SQLRETURN BindParameters(SQLHANDLE hStmt, const py::list& params,
std::vector<ParamInfo>& paramInfos,
std::vector<std::shared_ptr<void>>& paramBuffers,
const std::string& charEncoding = "utf-8") {
LOG("BindParameters: Starting parameter binding for statement handle %p "
"with %zu parameters",
(void*)hStmt, params.size());
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->c_str()));
bufferLength = strParam->size() + 1;
strLenOrIndPtr = AllocateParamBuffer<SQLLEN>(paramBuffers);
*strLenOrIndPtr = SQL_NTS;
}
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::wstring* strParam =
AllocateParamBuffer<std::wstring>(paramBuffers, param.cast<std::wstring>());
LOG("BindParameters: param[%d] SQL_C_WCHAR - String "
"length=%zu characters, buffer=%zu bytes",
paramIndex, strParam->size(), strParam->size() * sizeof(SQLWCHAR));
std::vector<SQLWCHAR>* sqlwcharBuffer =
AllocateParamBuffer<std::vector<SQLWCHAR>>(paramBuffers,
WStringToSQLWCHAR(*strParam));
dataPtr = sqlwcharBuffer->data();
bufferLength = sqlwcharBuffer->size() * sizeof(SQLWCHAR);
strLenOrIndPtr = AllocateParamBuffer<SQLLEN>(paramBuffers);
*strLenOrIndPtr = SQL_NTS;
}
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));
}
SQLSMALLINT sqlType = paramInfo.paramSQLType;
SQLULEN columnSize = paramInfo.columnSize;
SQLSMALLINT decimalDigits = paramInfo.decimalDigits;
if (sqlType == SQL_UNKNOWN_TYPE) {
SQLSMALLINT describedType;
SQLULEN describedSize;
SQLSMALLINT describedDigits;
SQLSMALLINT nullable;
RETCODE rc = SQLDescribeParam_ptr(
hStmt, static_cast<SQLUSMALLINT>(paramIndex + 1), &describedType,
&describedSize, &describedDigits, &nullable);
if (!SQL_SUCCEEDED(rc)) {
LOG("BindParameters: SQLDescribeParam failed for "
"param[%d] (NULL parameter) - SQLRETURN=%d",
paramIndex, rc);
return rc;
}
sqlType = describedType;
columnSize = describedSize;
decimalDigits = describedDigits;
}
dataPtr = nullptr;
strLenOrIndPtr = AllocateParamBuffer<SQLLEN>(paramBuffers);
*strLenOrIndPtr = SQL_NULL_DATA;
bufferLength = 0;
paramInfo.paramSQLType = sqlType;
paramInfo.columnSize = columnSize;
paramInfo.decimalDigits = decimalDigits;
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));
}
int64_t value = param.cast<int64_t>();
// Range validation for signed 64-bit integer
if (value < std::numeric_limits<int64_t>::min() ||
value > std::numeric_limits<int64_t>::max()) {
ThrowStdException("Signed 64-bit integer parameter out of "
"range at paramIndex " +
std::to_string(paramIndex));
}
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));
}
uint64_t value = param.cast<uint64_t>();
// Range validation for unsigned 64-bit integer
if (value > std::numeric_limits<uint64_t>::max()) {
ThrowStdException("Unsigned 64-bit integer parameter out "
"of range at paramIndex " +
std::to_string(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 = PythonObjectCache::get_date_class();
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 = PythonObjectCache::get_time_class();
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 = PythonObjectCache::get_datetime_class();
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 = PythonObjectCache::get_datetime_class();
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 = 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) {
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, 1, 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, 1, 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, 1, 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, 1, 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
static bool is_python_finalizing() {
try {
if (Py_IsInitialized() == 0) {
return true; // Python is already shut down
}
py::gil_scoped_acquire gil;
py::object sys_module = py::module_::import("sys");
if (!sys_module.is_none()) {
// Check if the attribute exists before accessing it (for Python
// version compatibility)
if (py::hasattr(sys_module, "_is_finalizing")) {
py::object finalizing_func = sys_module.attr("_is_finalizing");
if (!finalizing_func.is_none() && finalizing_func().cast<bool>()) {
return true; // Python is finalizing
}
}
}
return false;
} catch (...) {
std::cerr << "Error occurred while checking Python finalization state." << std::endl;
// Be conservative - don't assume shutdown on any exception
// Only return true if we're absolutely certain Python is shutting down
return false;
}
}
// TODO: Add more nuanced exception classes
void ThrowStdException(const std::string& message) {
throw std::runtime_error(message);
}
std::string GetLastErrorMessage();
// TODO: Move this to Python
std::string GetModuleDirectory() {
py::object module = py::module::import("mssql_python");
py::object module_path = module.attr("__file__");
std::string module_file = module_path.cast<std::string>();
#ifdef _WIN32
// Windows-specific path handling
char path[MAX_PATH];
errno_t err = strncpy_s(path, MAX_PATH, module_file.c_str(), module_file.length());
if (err != 0) {
LOG("GetModuleDirectory: strncpy_s failed copying path - "
"error_code=%d, path_length=%zu",
err, module_file.length());
return {};
}
PathRemoveFileSpecA(path);
return std::string(path);
#else
// macOS/Unix path handling without using std::filesystem
std::string::size_type pos = module_file.find_last_of('/');
if (pos != std::string::npos) {
std::string dir = module_file.substr(0, pos);
return dir;
}
LOG("GetModuleDirectory: Could not extract directory from module path - "
"path='%s'",
module_file.c_str());
return module_file;
#endif
}
// Platform-agnostic function to load the driver dynamic library
DriverHandle LoadDriverLibrary(const std::string& driverPath) {
LOG("LoadDriverLibrary: Attempting to load ODBC driver from path='%s'", driverPath.c_str());
#ifdef _WIN32
// Windows: Convert string to wide string for LoadLibraryW
std::wstring widePath(driverPath.begin(), driverPath.end());
HMODULE handle = LoadLibraryW(widePath.c_str());
if (!handle) {
LOG("LoadDriverLibrary: LoadLibraryW failed for path='%s' - %s", driverPath.c_str(),
GetLastErrorMessage().c_str());
ThrowStdException("Failed to load library: " + driverPath);
}
return handle;
#else
// macOS/Unix: Use dlopen
void* handle = dlopen(driverPath.c_str(), RTLD_LAZY);
if (!handle) {
LOG("LoadDriverLibrary: dlopen failed for path='%s' - %s", driverPath.c_str(),
dlerror() ? dlerror() : "unknown error");
}
return handle;
#endif
}
// Platform-agnostic function to get last error message
std::string GetLastErrorMessage() {
#ifdef _WIN32
// Windows: Use FormatMessageA
DWORD error = GetLastError();
char* messageBuffer = nullptr;
size_t size = FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
std::string errorMessage = messageBuffer ? std::string(messageBuffer, size) : "Unknown error";
LocalFree(messageBuffer);
return "Error code: " + std::to_string(error) + " - " + errorMessage;
#else
// macOS/Unix: Use dlerror
const char* error = dlerror();
return error ? std::string(error) : "Unknown error";
#endif
}
/*
* Resolve ODBC driver path in C++ to avoid circular import issues on Alpine.
*
* Background:
* On Alpine Linux, calling into Python during module initialization (via
* pybind11) causes a circular import due to musl's stricter dynamic loader
* behavior.
*
* Specifically, importing Python helpers from C++ triggered a re-import of the
* partially-initialized native module, which works on glibc (Ubuntu/macOS) but
* fails on musl-based systems like Alpine.
*
* By moving driver path resolution entirely into C++, we avoid any Python-layer
* dependencies during critical initialization, ensuring compatibility across
* all supported platforms.
*/
std::string GetDriverPathCpp(const std::string& moduleDir) {
namespace fs = std::filesystem;
fs::path basePath(moduleDir);
std::string platform;
std::string arch;
// Detect architecture
#if defined(__aarch64__) || defined(_M_ARM64)
arch = "arm64";
#elif defined(__x86_64__) || defined(_M_X64) || defined(_M_AMD64)
arch = "x86_64"; // maps to "x64" on Windows
#else
throw std::runtime_error("Unsupported architecture");
#endif
// Detect platform and set path
#ifdef __linux__
if (fs::exists("/etc/alpine-release")) {
platform = "alpine";
} else if (fs::exists("/etc/redhat-release") || fs::exists("/etc/centos-release")) {
platform = "rhel";
} else if (fs::exists("/etc/SuSE-release") || fs::exists("/etc/SUSE-brand")) {
platform = "suse";
} else {
platform = "debian_ubuntu"; // Default to debian_ubuntu for other distros
}
fs::path driverPath =
basePath / "libs" / "linux" / platform / arch / "lib" / "libmsodbcsql-18.5.so.1.1";
return driverPath.string();
#elif defined(__APPLE__)
platform = "macos";
fs::path driverPath = basePath / "libs" / platform / arch / "lib" / "libmsodbcsql.18.dylib";
return driverPath.string();
#elif defined(_WIN32)
platform = "windows";
// Normalize x86_64 to x64 for Windows naming
if (arch == "x86_64")
arch = "x64";
fs::path driverPath = basePath / "libs" / platform / arch / "msodbcsql18.dll";
return driverPath.string();
#else
throw std::runtime_error("Unsupported platform");
#endif
}
DriverHandle LoadDriverOrThrowException() {
namespace fs = std::filesystem;
std::string moduleDir = GetModuleDirectory();
LOG("LoadDriverOrThrowException: Module directory resolved to '%s'", moduleDir.c_str());
std::string archStr = ARCHITECTURE;
LOG("LoadDriverOrThrowException: Architecture detected as '%s'", archStr.c_str());
// Use only C++ function for driver path resolution
// Not using Python function since it causes circular import issues on
// Alpine Linux and other platforms with strict module loading rules.
std::string driverPathStr = GetDriverPathCpp(moduleDir);