forked from microsoft/mssql-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathddbc_bindings.h
More file actions
378 lines (335 loc) · 15 KB
/
ddbc_bindings.h
File metadata and controls
378 lines (335 loc) · 15 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
// 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 future.
#pragma once
#include <pybind11/pybind11.h> // pybind11.h must be the first include - https://pybind11.readthedocs.io/en/latest/basics.html#header-and-namespace-conventions
#include <pybind11/chrono.h>
#include <pybind11/complex.h>
#include <pybind11/functional.h>
#include <pybind11/pytypes.h> // Add this line for datetime support
#include <pybind11/stl.h>
namespace py = pybind11;
using namespace pybind11::literals;
#include <string>
#include <memory>
#include <mutex>
#ifdef _WIN32
// Windows-specific headers
#include <Windows.h> // windows.h needs to be included before sql.h
#include <shlwapi.h>
#pragma comment(lib, "shlwapi.lib")
#define IS_WINDOWS 1
#else
#define IS_WINDOWS 0
#endif
#include <sql.h>
#include <sqlext.h>
#if defined(_WIN32)
inline std::vector<SQLWCHAR> WStringToSQLWCHAR(const std::wstring& str) {
std::vector<SQLWCHAR> result(str.begin(), str.end());
result.push_back(0);
return result;
}
#endif
#if defined(__APPLE__) || defined(__linux__)
#include <dlfcn.h>
// Unicode constants for surrogate ranges and max scalar value
constexpr uint32_t UNICODE_SURROGATE_HIGH_START = 0xD800;
constexpr uint32_t UNICODE_SURROGATE_HIGH_END = 0xDBFF;
constexpr uint32_t UNICODE_SURROGATE_LOW_START = 0xDC00;
constexpr uint32_t UNICODE_SURROGATE_LOW_END = 0xDFFF;
constexpr uint32_t UNICODE_MAX_CODEPOINT = 0x10FFFF;
constexpr uint32_t UNICODE_REPLACEMENT_CHAR = 0xFFFD;
// Validate whether a code point is a legal Unicode scalar value
// (excludes surrogate halves and values beyond U+10FFFF)
inline bool IsValidUnicodeScalar(uint32_t cp) {
return cp <= UNICODE_MAX_CODEPOINT &&
!(cp >= UNICODE_SURROGATE_HIGH_START && cp <= UNICODE_SURROGATE_LOW_END);
}
inline std::wstring SQLWCHARToWString(const SQLWCHAR* sqlwStr, size_t length = SQL_NTS) {
if (!sqlwStr) return std::wstring();
if (length == SQL_NTS) {
size_t i = 0;
while (sqlwStr[i] != 0) ++i;
length = i;
}
std::wstring result;
result.reserve(length);
if constexpr (sizeof(SQLWCHAR) == 2) {
// Decode UTF-16 to UTF-32 (with surrogate pair handling)
for (size_t i = 0; i < length; ++i) {
uint16_t wc = static_cast<uint16_t>(sqlwStr[i]);
// Check if this is a high surrogate (U+D800–U+DBFF)
if (wc >= UNICODE_SURROGATE_HIGH_START && wc <= UNICODE_SURROGATE_HIGH_END && i + 1 < length) {
uint16_t low = static_cast<uint16_t>(sqlwStr[i + 1]);
// Check if the next code unit is a low surrogate (U+DC00–U+DFFF)
if (low >= UNICODE_SURROGATE_LOW_START && low <= UNICODE_SURROGATE_LOW_END) {
// Combine surrogate pair into a single code point
uint32_t cp = (((wc - UNICODE_SURROGATE_HIGH_START) << 10) | (low - UNICODE_SURROGATE_LOW_START)) + 0x10000;
result.push_back(static_cast<wchar_t>(cp));
++i; // Skip the low surrogate
continue;
}
}
// If valid scalar then append, else append replacement char (U+FFFD)
if (IsValidUnicodeScalar(wc)) {
result.push_back(static_cast<wchar_t>(wc));
} else {
result.push_back(static_cast<wchar_t>(UNICODE_REPLACEMENT_CHAR));
}
}
} else {
// SQLWCHAR is UTF-32, so just copy with validation
for (size_t i = 0; i < length; ++i) {
uint32_t cp = static_cast<uint32_t>(sqlwStr[i]);
if (IsValidUnicodeScalar(cp)) {
result.push_back(static_cast<wchar_t>(cp));
} else {
result.push_back(static_cast<wchar_t>(UNICODE_REPLACEMENT_CHAR));
}
}
}
return result;
}
inline std::vector<SQLWCHAR> WStringToSQLWCHAR(const std::wstring& str) {
std::vector<SQLWCHAR> result;
result.reserve(str.size() + 2);
if constexpr (sizeof(SQLWCHAR) == 2) {
// Encode UTF-32 to UTF-16
for (wchar_t wc : str) {
uint32_t cp = static_cast<uint32_t>(wc);
if (!IsValidUnicodeScalar(cp)) {
cp = UNICODE_REPLACEMENT_CHAR;
}
if (cp <= 0xFFFF) {
// Fits in a single UTF-16 code unit
result.push_back(static_cast<SQLWCHAR>(cp));
} else {
// Encode as surrogate pair
cp -= 0x10000;
SQLWCHAR high = static_cast<SQLWCHAR>((cp >> 10) + UNICODE_SURROGATE_HIGH_START);
SQLWCHAR low = static_cast<SQLWCHAR>((cp & 0x3FF) + UNICODE_SURROGATE_LOW_START);
result.push_back(high);
result.push_back(low);
}
}
} else {
// Encode UTF-32 directly
for (wchar_t wc : str) {
uint32_t cp = static_cast<uint32_t>(wc);
if (IsValidUnicodeScalar(cp)) {
result.push_back(static_cast<SQLWCHAR>(cp));
} else {
result.push_back(static_cast<SQLWCHAR>(UNICODE_REPLACEMENT_CHAR));
}
}
}
result.push_back(0); // null terminator
return result;
}
#endif
#if defined(__APPLE__) || defined(__linux__)
#include "unix_utils.h" // For Unix-specific Unicode encoding fixes
#include "unix_buffers.h" // For Unix-specific buffer handling
#endif
//-------------------------------------------------------------------------------------------------
// Function pointer typedefs
//-------------------------------------------------------------------------------------------------
// Handle APIs
typedef SQLRETURN (SQL_API* SQLAllocHandleFunc)(SQLSMALLINT, SQLHANDLE, SQLHANDLE*);
typedef SQLRETURN (SQL_API* SQLSetEnvAttrFunc)(SQLHANDLE, SQLINTEGER, SQLPOINTER, SQLINTEGER);
typedef SQLRETURN (SQL_API* SQLSetConnectAttrFunc)(SQLHDBC, SQLINTEGER, SQLPOINTER, SQLINTEGER);
typedef SQLRETURN (SQL_API* SQLSetStmtAttrFunc)(SQLHSTMT, SQLINTEGER, SQLPOINTER, SQLINTEGER);
typedef SQLRETURN (SQL_API* SQLGetConnectAttrFunc)(SQLHDBC, SQLINTEGER, SQLPOINTER, SQLINTEGER, SQLINTEGER*);
// Connection and Execution APIs
typedef SQLRETURN (SQL_API* SQLDriverConnectFunc)(SQLHANDLE, SQLHWND, SQLWCHAR*, SQLSMALLINT, SQLWCHAR*,
SQLSMALLINT, SQLSMALLINT*, SQLUSMALLINT);
typedef SQLRETURN (SQL_API* SQLExecDirectFunc)(SQLHANDLE, SQLWCHAR*, SQLINTEGER);
typedef SQLRETURN (SQL_API* SQLPrepareFunc)(SQLHANDLE, SQLWCHAR*, SQLINTEGER);
typedef SQLRETURN (SQL_API* SQLBindParameterFunc)(SQLHANDLE, SQLUSMALLINT, SQLSMALLINT, SQLSMALLINT,
SQLSMALLINT, SQLULEN, SQLSMALLINT, SQLPOINTER, SQLLEN,
SQLLEN*);
typedef SQLRETURN (SQL_API* SQLExecuteFunc)(SQLHANDLE);
typedef SQLRETURN (SQL_API* SQLRowCountFunc)(SQLHSTMT, SQLLEN*);
typedef SQLRETURN (SQL_API* SQLSetDescFieldFunc)(SQLHDESC, SQLSMALLINT, SQLSMALLINT, SQLPOINTER, SQLINTEGER);
typedef SQLRETURN (SQL_API* SQLGetStmtAttrFunc)(SQLHSTMT, SQLINTEGER, SQLPOINTER, SQLINTEGER, SQLINTEGER*);
// Data retrieval APIs
typedef SQLRETURN (SQL_API* SQLFetchFunc)(SQLHANDLE);
typedef SQLRETURN (SQL_API* SQLFetchScrollFunc)(SQLHANDLE, SQLSMALLINT, SQLLEN);
typedef SQLRETURN (SQL_API* SQLGetDataFunc)(SQLHANDLE, SQLUSMALLINT, SQLSMALLINT, SQLPOINTER, SQLLEN,
SQLLEN*);
typedef SQLRETURN (SQL_API* SQLNumResultColsFunc)(SQLHSTMT, SQLSMALLINT*);
typedef SQLRETURN (SQL_API* SQLBindColFunc)(SQLHSTMT, SQLUSMALLINT, SQLSMALLINT, SQLPOINTER, SQLLEN,
SQLLEN*);
typedef SQLRETURN (SQL_API* SQLDescribeColFunc)(SQLHSTMT, SQLUSMALLINT, SQLWCHAR*, SQLSMALLINT,
SQLSMALLINT*, SQLSMALLINT*, SQLULEN*, SQLSMALLINT*,
SQLSMALLINT*);
typedef SQLRETURN (SQL_API* SQLMoreResultsFunc)(SQLHSTMT);
typedef SQLRETURN (SQL_API* SQLColAttributeFunc)(SQLHSTMT, SQLUSMALLINT, SQLUSMALLINT, SQLPOINTER,
SQLSMALLINT, SQLSMALLINT*, SQLPOINTER);
typedef SQLRETURN (*SQLTablesFunc)(
SQLHSTMT StatementHandle,
SQLWCHAR* CatalogName,
SQLSMALLINT NameLength1,
SQLWCHAR* SchemaName,
SQLSMALLINT NameLength2,
SQLWCHAR* TableName,
SQLSMALLINT NameLength3,
SQLWCHAR* TableType,
SQLSMALLINT NameLength4
);
// Transaction APIs
typedef SQLRETURN (SQL_API* SQLEndTranFunc)(SQLSMALLINT, SQLHANDLE, SQLSMALLINT);
// Disconnect/free APIs
typedef SQLRETURN (SQL_API* SQLFreeHandleFunc)(SQLSMALLINT, SQLHANDLE);
typedef SQLRETURN (SQL_API* SQLDisconnectFunc)(SQLHDBC);
typedef SQLRETURN (SQL_API* SQLFreeStmtFunc)(SQLHSTMT, SQLUSMALLINT);
// Diagnostic APIs
typedef SQLRETURN (SQL_API* SQLGetDiagRecFunc)(SQLSMALLINT, SQLHANDLE, SQLSMALLINT, SQLWCHAR*, SQLINTEGER*,
SQLWCHAR*, SQLSMALLINT, SQLSMALLINT*);
typedef SQLRETURN (SQL_API* SQLDescribeParamFunc)(SQLHSTMT, SQLUSMALLINT, SQLSMALLINT*, SQLULEN*, SQLSMALLINT*, SQLSMALLINT*);
// DAE APIs
typedef SQLRETURN (SQL_API* SQLParamDataFunc)(SQLHSTMT, SQLPOINTER*);
typedef SQLRETURN (SQL_API* SQLPutDataFunc)(SQLHSTMT, SQLPOINTER, SQLLEN);
//-------------------------------------------------------------------------------------------------
// Extern function pointer declarations (defined in ddbc_bindings.cpp)
//-------------------------------------------------------------------------------------------------
// Handle APIs
extern SQLAllocHandleFunc SQLAllocHandle_ptr;
extern SQLSetEnvAttrFunc SQLSetEnvAttr_ptr;
extern SQLSetConnectAttrFunc SQLSetConnectAttr_ptr;
extern SQLSetStmtAttrFunc SQLSetStmtAttr_ptr;
extern SQLGetConnectAttrFunc SQLGetConnectAttr_ptr;
// Connection and Execution APIs
extern SQLDriverConnectFunc SQLDriverConnect_ptr;
extern SQLExecDirectFunc SQLExecDirect_ptr;
extern SQLPrepareFunc SQLPrepare_ptr;
extern SQLBindParameterFunc SQLBindParameter_ptr;
extern SQLExecuteFunc SQLExecute_ptr;
extern SQLRowCountFunc SQLRowCount_ptr;
extern SQLSetDescFieldFunc SQLSetDescField_ptr;
extern SQLGetStmtAttrFunc SQLGetStmtAttr_ptr;
// Data retrieval APIs
extern SQLFetchFunc SQLFetch_ptr;
extern SQLFetchScrollFunc SQLFetchScroll_ptr;
extern SQLGetDataFunc SQLGetData_ptr;
extern SQLNumResultColsFunc SQLNumResultCols_ptr;
extern SQLBindColFunc SQLBindCol_ptr;
extern SQLDescribeColFunc SQLDescribeCol_ptr;
extern SQLMoreResultsFunc SQLMoreResults_ptr;
extern SQLColAttributeFunc SQLColAttribute_ptr;
extern SQLTablesFunc SQLTables_ptr;
// Transaction APIs
extern SQLEndTranFunc SQLEndTran_ptr;
// Disconnect/free APIs
extern SQLFreeHandleFunc SQLFreeHandle_ptr;
extern SQLDisconnectFunc SQLDisconnect_ptr;
extern SQLFreeStmtFunc SQLFreeStmt_ptr;
// Diagnostic APIs
extern SQLGetDiagRecFunc SQLGetDiagRec_ptr;
extern SQLDescribeParamFunc SQLDescribeParam_ptr;
// DAE APIs
extern SQLParamDataFunc SQLParamData_ptr;
extern SQLPutDataFunc SQLPutData_ptr;
// Logging utility
template <typename... Args>
void LOG(const std::string& formatString, Args&&... args);
// Throws a std::runtime_error with the given message
void ThrowStdException(const std::string& message);
// Define a platform-agnostic type for the driver handle
#ifdef _WIN32
typedef HMODULE DriverHandle;
#else
typedef void* DriverHandle;
#endif
// Platform-agnostic function to get a function pointer from the loaded library
template<typename T>
T GetFunctionPointer(DriverHandle handle, const char* functionName) {
#ifdef _WIN32
// Windows: Use GetProcAddress
return reinterpret_cast<T>(GetProcAddress(handle, functionName));
#else
// macOS/Unix: Use dlsym
return reinterpret_cast<T>(dlsym(handle, functionName));
#endif
}
//-------------------------------------------------------------------------------------------------
// Loads the ODBC driver and resolves function pointers.
// Throws if loading or resolution fails.
//-------------------------------------------------------------------------------------------------
DriverHandle LoadDriverOrThrowException();
//-------------------------------------------------------------------------------------------------
// DriverLoader (Singleton)
//
// Ensures the ODBC driver and all function pointers are loaded exactly once across the process.
// This avoids redundant work and ensures thread-safe, centralized initialization.
//
// Not copyable or assignable.
//-------------------------------------------------------------------------------------------------
class DriverLoader {
public:
static DriverLoader& getInstance();
void loadDriver();
private:
DriverLoader();
DriverLoader(const DriverLoader&) = delete;
DriverLoader& operator=(const DriverLoader&) = delete;
bool m_driverLoaded;
std::once_flag m_onceFlag;
};
//-------------------------------------------------------------------------------------------------
// SqlHandle
//
// RAII wrapper around ODBC handles (ENV, DBC, STMT).
// Use `std::shared_ptr<SqlHandle>` (alias: SqlHandlePtr) for shared ownership.
//-------------------------------------------------------------------------------------------------
class SqlHandle {
public:
SqlHandle(SQLSMALLINT type, SQLHANDLE rawHandle);
~SqlHandle();
SQLHANDLE get() const;
SQLSMALLINT type() const;
void free();
private:
SQLSMALLINT _type;
SQLHANDLE _handle;
};
using SqlHandlePtr = std::shared_ptr<SqlHandle>;
// This struct is used to relay error info obtained from SQLDiagRec API to the Python module
struct ErrorInfo {
std::wstring sqlState;
std::wstring ddbcErrorMsg;
};
ErrorInfo SQLCheckError_Wrap(SQLSMALLINT handleType, SqlHandlePtr handle, SQLRETURN retcode);
inline std::string WideToUTF8(const std::wstring& wstr) {
if (wstr.empty()) return {};
#if defined(_WIN32)
int size_needed = WideCharToMultiByte(CP_UTF8, 0, wstr.data(), static_cast<int>(wstr.size()), nullptr, 0, nullptr, nullptr);
if (size_needed == 0) return {};
std::string result(size_needed, 0);
int converted = WideCharToMultiByte(CP_UTF8, 0, wstr.data(), static_cast<int>(wstr.size()), result.data(), size_needed, nullptr, nullptr);
if (converted == 0) return {};
return result;
#else
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return converter.to_bytes(wstr);
#endif
}
inline std::wstring Utf8ToWString(const std::string& str) {
if (str.empty()) return {};
#if defined(_WIN32)
int size_needed = MultiByteToWideChar(CP_UTF8, 0, str.data(), static_cast<int>(str.size()), nullptr, 0);
if (size_needed == 0) {
LOG("MultiByteToWideChar failed.");
return {};
}
std::wstring result(size_needed, 0);
int converted = MultiByteToWideChar(CP_UTF8, 0, str.data(), static_cast<int>(str.size()), result.data(), size_needed);
if (converted == 0) return {};
return result;
#else
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return converter.from_bytes(str);
#endif
}