-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathconnection.cpp
More file actions
382 lines (335 loc) · 12 KB
/
connection.cpp
File metadata and controls
382 lines (335 loc) · 12 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
// 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
#include "connection.h"
#include "connection_pool.h"
#include <vector>
#include <pybind11/pybind11.h>
#define SQL_COPT_SS_ACCESS_TOKEN 1256 // Custom attribute ID for access token
#define SQL_MAX_SMALL_INT 32767 // Maximum value for SQLSMALLINT
static SqlHandlePtr getEnvHandle() {
static SqlHandlePtr envHandle = []() -> SqlHandlePtr {
LOG("Allocating ODBC environment handle");
if (!SQLAllocHandle_ptr) {
LOG("Function pointers not initialized, loading driver");
DriverLoader::getInstance().loadDriver();
}
SQLHANDLE env = nullptr;
SQLRETURN ret = SQLAllocHandle_ptr(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
if (!SQL_SUCCEEDED(ret)) {
ThrowStdException("Failed to allocate environment handle");
}
ret = SQLSetEnvAttr_ptr(env, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3_80, 0);
if (!SQL_SUCCEEDED(ret)) {
ThrowStdException("Failed to set environment attributes");
}
return std::make_shared<SqlHandle>(static_cast<SQLSMALLINT>(SQL_HANDLE_ENV), env);
}();
return envHandle;
}
//-------------------------------------------------------------------------------------------------
// Implements the Connection class declared in connection.h.
// This class wraps low-level ODBC operations like connect/disconnect,
// transaction control, and autocommit configuration.
//-------------------------------------------------------------------------------------------------
Connection::Connection(const std::wstring& conn_str, bool use_pool)
: _connStr(conn_str), _autocommit(false), _fromPool(use_pool) {
allocateDbcHandle();
}
Connection::~Connection() {
disconnect(); // fallback if user forgets to disconnect
}
// Allocates connection handle
void Connection::allocateDbcHandle() {
auto _envHandle = getEnvHandle();
SQLHANDLE dbc = nullptr;
LOG("Allocate SQL Connection Handle");
SQLRETURN ret = SQLAllocHandle_ptr(SQL_HANDLE_DBC, _envHandle->get(), &dbc);
checkError(ret);
_dbcHandle = std::make_shared<SqlHandle>(static_cast<SQLSMALLINT>(SQL_HANDLE_DBC), dbc);
}
void Connection::connect(const py::dict& attrs_before) {
LOG("Connecting to database");
// Apply access token before connect
if (!attrs_before.is_none() && py::len(attrs_before) > 0) {
LOG("Apply attributes before connect");
applyAttrsBefore(attrs_before);
if (_autocommit) {
setAutocommit(_autocommit);
}
}
SQLWCHAR* connStrPtr;
#if defined(__APPLE__) || defined(__linux__) // macOS/Linux specific handling
LOG("Creating connection string buffer for macOS/Linux");
std::vector<SQLWCHAR> connStrBuffer = WStringToSQLWCHAR(_connStr);
// Ensure the buffer is null-terminated
LOG("Connection string buffer size - {}", connStrBuffer.size());
connStrPtr = connStrBuffer.data();
LOG("Connection string buffer created");
#else
connStrPtr = const_cast<SQLWCHAR*>(_connStr.c_str());
#endif
SQLRETURN ret = SQLDriverConnect_ptr(
_dbcHandle->get(), nullptr,
connStrPtr, SQL_NTS,
nullptr, 0, nullptr, SQL_DRIVER_NOPROMPT);
checkError(ret);
updateLastUsed();
}
void Connection::disconnect() {
if (_dbcHandle) {
LOG("Disconnecting from database");
SQLRETURN ret = SQLDisconnect_ptr(_dbcHandle->get());
checkError(ret);
_dbcHandle.reset(); // triggers SQLFreeHandle via destructor, if last owner
}
else {
LOG("No connection handle to disconnect");
}
}
// TODO: Add an exception class in C++ for error handling, DB spec compliant
void Connection::checkError(SQLRETURN ret) const{
if (!SQL_SUCCEEDED(ret)) {
ErrorInfo err = SQLCheckError_Wrap(SQL_HANDLE_DBC, _dbcHandle, ret);
std::string errorMsg = WideToUTF8(err.ddbcErrorMsg);
ThrowStdException(errorMsg);
}
}
void Connection::commit() {
if (!_dbcHandle) {
ThrowStdException("Connection handle not allocated");
}
updateLastUsed();
LOG("Committing transaction");
SQLRETURN ret = SQLEndTran_ptr(SQL_HANDLE_DBC, _dbcHandle->get(), SQL_COMMIT);
checkError(ret);
}
void Connection::rollback() {
if (!_dbcHandle) {
ThrowStdException("Connection handle not allocated");
}
updateLastUsed();
LOG("Rolling back transaction");
SQLRETURN ret = SQLEndTran_ptr(SQL_HANDLE_DBC, _dbcHandle->get(), SQL_ROLLBACK);
checkError(ret);
}
void Connection::setAutocommit(bool enable) {
if (!_dbcHandle) {
ThrowStdException("Connection handle not allocated");
}
SQLINTEGER value = enable ? SQL_AUTOCOMMIT_ON : SQL_AUTOCOMMIT_OFF;
LOG("Setting SQL Connection Attribute");
SQLRETURN ret = SQLSetConnectAttr_ptr(_dbcHandle->get(), SQL_ATTR_AUTOCOMMIT, reinterpret_cast<SQLPOINTER>(static_cast<SQLULEN>(value)), 0);
checkError(ret);
if(value == SQL_AUTOCOMMIT_ON) {
LOG("SQL Autocommit set to True");
} else {
LOG("SQL Autocommit set to False");
}
_autocommit = enable;
}
bool Connection::getAutocommit() const {
if (!_dbcHandle) {
ThrowStdException("Connection handle not allocated");
}
LOG("Get SQL Connection Attribute");
SQLINTEGER value;
SQLINTEGER string_length;
SQLRETURN ret = SQLGetConnectAttr_ptr(_dbcHandle->get(), SQL_ATTR_AUTOCOMMIT, &value, sizeof(value), &string_length);
checkError(ret);
return value == SQL_AUTOCOMMIT_ON;
}
SqlHandlePtr Connection::allocStatementHandle() {
if (!_dbcHandle) {
ThrowStdException("Connection handle not allocated");
}
updateLastUsed();
LOG("Allocating statement handle");
SQLHANDLE stmt = nullptr;
SQLRETURN ret = SQLAllocHandle_ptr(SQL_HANDLE_STMT, _dbcHandle->get(), &stmt);
checkError(ret);
return std::make_shared<SqlHandle>(static_cast<SQLSMALLINT>(SQL_HANDLE_STMT), stmt);
}
SQLRETURN Connection::setAttribute(SQLINTEGER attribute, py::object value) {
LOG("Setting SQL attribute");
SQLPOINTER ptr = nullptr;
SQLINTEGER length = 0;
static std::string buffer; // to hold sensitive data temporarily
if (py::isinstance<py::int_>(value)) {
int intValue = value.cast<int>();
ptr = reinterpret_cast<SQLPOINTER>(static_cast<uintptr_t>(intValue));
length = SQL_IS_INTEGER;
} else if (py::isinstance<py::bytes>(value) || py::isinstance<py::bytearray>(value)) {
buffer = value.cast<std::string>(); // stack buffer
ptr = buffer.data();
length = static_cast<SQLINTEGER>(buffer.size());
} else {
LOG("Unsupported attribute value type");
return SQL_ERROR;
}
SQLRETURN ret = SQLSetConnectAttr_ptr(_dbcHandle->get(), attribute, ptr, length);
if (!SQL_SUCCEEDED(ret)) {
LOG("Failed to set attribute");
}
else {
LOG("Set attribute successfully");
}
return ret;
}
void Connection::applyAttrsBefore(const py::dict& attrs) {
for (const auto& item : attrs) {
int key;
try {
key = py::cast<int>(item.first);
} catch (...) {
continue;
}
if (key == SQL_COPT_SS_ACCESS_TOKEN) {
SQLRETURN ret = setAttribute(key, py::reinterpret_borrow<py::object>(item.second));
if (!SQL_SUCCEEDED(ret)) {
ThrowStdException("Failed to set access token before connect");
}
}
}
}
bool Connection::isAlive() const {
if (!_dbcHandle) {
ThrowStdException("Connection handle not allocated");
}
SQLUINTEGER status;
SQLRETURN ret = SQLGetConnectAttr_ptr(_dbcHandle->get(), SQL_ATTR_CONNECTION_DEAD,
&status, 0, nullptr);
return SQL_SUCCEEDED(ret) && status == SQL_CD_FALSE;
}
bool Connection::reset() {
if (!_dbcHandle) {
ThrowStdException("Connection handle not allocated");
}
LOG("Resetting connection via SQL_ATTR_RESET_CONNECTION");
SQLRETURN ret = SQLSetConnectAttr_ptr(
_dbcHandle->get(),
SQL_ATTR_RESET_CONNECTION,
(SQLPOINTER)SQL_RESET_CONNECTION_YES,
SQL_IS_INTEGER);
if (!SQL_SUCCEEDED(ret)) {
LOG("Failed to reset connection. Marking as dead.");
disconnect();
return false;
}
updateLastUsed();
return true;
}
void Connection::updateLastUsed() {
_lastUsed = std::chrono::steady_clock::now();
}
std::chrono::steady_clock::time_point Connection::lastUsed() const {
return _lastUsed;
}
ConnectionHandle::ConnectionHandle(const std::string& connStr, bool usePool, const py::dict& attrsBefore)
: _usePool(usePool) {
_connStr = Utf8ToWString(connStr);
if (_usePool) {
_conn = ConnectionPoolManager::getInstance().acquireConnection(_connStr, attrsBefore);
} else {
_conn = std::make_shared<Connection>(_connStr, false);
_conn->connect(attrsBefore);
}
}
ConnectionHandle::~ConnectionHandle() {
if (_conn) {
close();
}
}
void ConnectionHandle::close() {
if (!_conn) {
ThrowStdException("Connection object is not initialized");
}
if (_usePool) {
ConnectionPoolManager::getInstance().returnConnection(_connStr, _conn);
} else {
_conn->disconnect();
}
_conn = nullptr;
}
void ConnectionHandle::commit() {
if (!_conn) {
ThrowStdException("Connection object is not initialized");
}
_conn->commit();
}
void ConnectionHandle::rollback() {
if (!_conn) {
ThrowStdException("Connection object is not initialized");
}
_conn->rollback();
}
void ConnectionHandle::setAutocommit(bool enabled) {
if (!_conn) {
ThrowStdException("Connection object is not initialized");
}
_conn->setAutocommit(enabled);
}
bool ConnectionHandle::getAutocommit() const {
if (!_conn) {
ThrowStdException("Connection object is not initialized");
}
return _conn->getAutocommit();
}
SqlHandlePtr ConnectionHandle::allocStatementHandle() {
if (!_conn) {
ThrowStdException("Connection object is not initialized");
}
return _conn->allocStatementHandle();
}
py::object Connection::getInfo(SQLUSMALLINT infoType) const {
if (!_dbcHandle) {
ThrowStdException("Connection handle not allocated");
}
// First call with NULL buffer to get required length
SQLSMALLINT requiredLen = 0;
SQLRETURN ret = SQLGetInfo_ptr(_dbcHandle->get(), infoType, NULL, 0, &requiredLen);
if (!SQL_SUCCEEDED(ret)) {
checkError(ret);
return py::none();
}
// For zero-length results
if (requiredLen == 0) {
py::dict result;
result["data"] = py::bytes("", 0);
result["length"] = 0;
result["info_type"] = infoType;
return result;
}
// Cap buffer allocation to SQL_MAX_SMALL_INT to prevent excessive memory usage
SQLSMALLINT allocSize = requiredLen + 10;
if (allocSize > SQL_MAX_SMALL_INT) {
allocSize = SQL_MAX_SMALL_INT;
}
std::vector<char> buffer(allocSize, 0); // Extra padding for safety
// Get the actual data - avoid using std::min
SQLSMALLINT bufferSize = requiredLen + 10;
if (bufferSize > SQL_MAX_SMALL_INT) {
bufferSize = SQL_MAX_SMALL_INT;
}
SQLSMALLINT returnedLen = 0;
ret = SQLGetInfo_ptr(_dbcHandle->get(), infoType, buffer.data(), bufferSize, &returnedLen);
if (!SQL_SUCCEEDED(ret)) {
checkError(ret);
return py::none();
}
// Create a dictionary with the raw data
py::dict result;
// IMPORTANT: Pass exactly what SQLGetInfo returned
// No null-terminator manipulation, just pass the raw data
result["data"] = py::bytes(buffer.data(), returnedLen);
result["length"] = returnedLen;
result["info_type"] = infoType;
return result;
}
py::object ConnectionHandle::getInfo(SQLUSMALLINT infoType) const {
if (!_conn) {
ThrowStdException("Connection object is not initialized");
}
return _conn->getInfo(infoType);
}