-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patholapclient.cpp
More file actions
380 lines (326 loc) · 12.2 KB
/
Copy patholapclient.cpp
File metadata and controls
380 lines (326 loc) · 12.2 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
// olapclient.cpp
// Implementation of the OLAP client DLL.
//
// Dependencies (Windows only):
// - msado15.dll : ADO COM objects (ships with Windows)
// - MSOLAP : Microsoft OLE DB Provider for Analysis Services
// Installed with SQL Server / SSMS / standalone download.
//
// Supports:
// - MDX queries against multidimensional SSAS cubes
// - DAX queries against tabular SSAS models (MSOLAP 11+)
// OLAPCLIENT_EXPORTS is defined by the project preprocessor settings.
// Do NOT redefine it here to avoid C4005 macro-redefinition warnings.
#include "olapclient.h"
#include <windows.h>
#include <comdef.h>
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>
// Import ADO type library by its registered GUID – avoids hard-coded file paths.
// GUID: {00000205-0000-0010-8000-00AA006D2EA4} = Microsoft ADO 6.x
#import "libid:00000205-0000-0010-8000-00AA006D2EA4" \
rename_namespace("ADODB") \
rename("EOF", "AdoEOF") \
rename("BOF", "AdoBOF")
// ---------------------------------------------------------------------------
// Internal structures
// ---------------------------------------------------------------------------
struct OlapConnection {
ADODB::_ConnectionPtr spConn;
};
struct OlapResult {
std::vector<std::string> colNames;
std::vector<std::vector<std::string>> rows;
};
// ---------------------------------------------------------------------------
// Thread-local error storage
// ---------------------------------------------------------------------------
static thread_local std::string g_lastError;
static void set_error(const std::string& msg) {
g_lastError = msg;
}
static void clear_error() {
g_lastError.clear();
}
// ---------------------------------------------------------------------------
// BSTR / VARIANT conversion helpers
// ---------------------------------------------------------------------------
static std::string bstr_to_utf8(BSTR bstr) {
if (!bstr) return std::string();
int len = WideCharToMultiByte(CP_UTF8, 0, bstr, -1, nullptr, 0, nullptr, nullptr);
if (len <= 0) return std::string();
std::string result(len - 1, '\0');
WideCharToMultiByte(CP_UTF8, 0, bstr, -1, &result[0], len, nullptr, nullptr);
return result;
}
static std::string variant_to_string(const _variant_t& v) {
if (v.vt == VT_NULL || v.vt == VT_EMPTY) return std::string();
try {
switch (v.vt) {
case VT_BSTR:
return bstr_to_utf8(v.bstrVal);
case VT_BOOL:
return v.boolVal ? "true" : "false";
case VT_I1: return std::to_string(static_cast<int>(v.cVal));
case VT_I2: return std::to_string(v.iVal);
case VT_I4: return std::to_string(v.lVal);
case VT_I8: return std::to_string(v.llVal);
case VT_UI1: return std::to_string(v.bVal);
case VT_UI2: return std::to_string(v.uiVal);
case VT_UI4: return std::to_string(v.ulVal);
case VT_UI8: return std::to_string(v.ullVal);
case VT_R4: {
std::ostringstream oss;
oss << std::setprecision(7) << v.fltVal;
return oss.str();
}
case VT_R8: {
std::ostringstream oss;
oss << std::setprecision(15) << v.dblVal;
return oss.str();
}
case VT_DECIMAL: {
// Convert DECIMAL to double via _variant_t cast
_variant_t dbl;
VariantChangeType(&dbl, const_cast<VARIANT*>(static_cast<const VARIANT*>(&v)),
0, VT_R8);
std::ostringstream oss;
oss << std::setprecision(15) << dbl.dblVal;
return oss.str();
}
case VT_CY: {
// Currency: CURRENCY = 64-bit int scaled by 10000
std::ostringstream oss;
oss << std::setprecision(4) << std::fixed
<< (static_cast<double>(v.cyVal.int64) / 10000.0);
return oss.str();
}
case VT_DATE: {
// OLE Automation date -> SYSTEMTIME string
SYSTEMTIME st{};
if (VariantTimeToSystemTime(v.date, &st)) {
char buf[32];
snprintf(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d:%02d",
st.wYear, st.wMonth, st.wDay,
st.wHour, st.wMinute, st.wSecond);
return buf;
}
// Fallback: raw double
std::ostringstream oss;
oss << v.date;
return oss.str();
}
default: {
// Try coercing to BSTR as a last resort
_variant_t tmp;
if (SUCCEEDED(VariantChangeType(&tmp, const_cast<VARIANT*>(
static_cast<const VARIANT*>(&v)), 0, VT_BSTR))) {
return bstr_to_utf8(tmp.bstrVal);
}
return std::string();
}
}
}
catch (...) {
return std::string();
}
}
// ---------------------------------------------------------------------------
// COM initialisation guard (per-thread, reference-counted)
// ---------------------------------------------------------------------------
struct ComInit {
bool ok;
ComInit() : ok(SUCCEEDED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))) {}
~ComInit() { if (ok) CoUninitialize(); }
};
static thread_local ComInit g_comInit;
// ---------------------------------------------------------------------------
// API implementation
// ---------------------------------------------------------------------------
OLAP_API OLAP_CONN olap_connect(const char* connection_string) {
clear_error();
if (!connection_string || !*connection_string) {
set_error("Connection string must not be empty.");
return nullptr;
}
// Ensure COM is initialised on this thread
if (!g_comInit.ok) {
set_error("CoInitializeEx failed.");
return nullptr;
}
auto* ctx = new (std::nothrow) OlapConnection();
if (!ctx) {
set_error("Out of memory.");
return nullptr;
}
try {
HRESULT hr = ctx->spConn.CreateInstance(__uuidof(ADODB::Connection));
if (FAILED(hr)) {
set_error("Failed to create ADO Connection object.");
delete ctx;
return nullptr;
}
// Convert UTF-8 connection string to wide, then to BSTR
int wlen = MultiByteToWideChar(CP_UTF8, 0, connection_string, -1, nullptr, 0);
std::wstring wcs(wlen, L'\0');
MultiByteToWideChar(CP_UTF8, 0, connection_string, -1, &wcs[0], wlen);
ctx->spConn->Open(_bstr_t(wcs.c_str()), L"", L"", ADODB::adConnectUnspecified);
}
catch (_com_error& ce) {
std::string msg = "Connection failed: ";
if (ce.Description().length() > 0)
msg += bstr_to_utf8(ce.Description());
else
msg += bstr_to_utf8(_bstr_t(ce.ErrorMessage()));
set_error(msg);
delete ctx;
return nullptr;
}
catch (...) {
set_error("Unknown exception during connection.");
delete ctx;
return nullptr;
}
return static_cast<OLAP_CONN>(ctx);
}
OLAP_API void olap_disconnect(OLAP_CONN conn) {
if (!conn) return;
auto* ctx = static_cast<OlapConnection*>(conn);
try {
if (ctx->spConn && ctx->spConn->State != ADODB::adStateClosed)
ctx->spConn->Close();
}
catch (...) {}
delete ctx;
}
OLAP_API int olap_is_connected(OLAP_CONN conn) {
if (!conn) return 0;
auto* ctx = static_cast<OlapConnection*>(conn);
try {
return (ctx->spConn && ctx->spConn->State == ADODB::adStateOpen) ? 1 : 0;
}
catch (...) {
return 0;
}
}
OLAP_API OLAP_RESULT olap_execute(OLAP_CONN conn, const char* query, int query_type) {
clear_error();
if (!conn) {
set_error("Invalid connection handle.");
return nullptr;
}
if (!query || !*query) {
set_error("Query must not be empty.");
return nullptr;
}
auto* ctx = static_cast<OlapConnection*>(conn);
auto* res = new (std::nothrow) OlapResult();
if (!res) {
set_error("Out of memory.");
return nullptr;
}
try {
// For DAX queries on tabular models, MSOLAP 11+ auto-detects the dialect.
// If needed, we can set the "Dialect" connection property to force DAX:
// GUID {C8B522D7-5CF3-11CE-ADE5-00AA0044773D} = MDX
// GUID {ED4E3EA1-6F82-4C7C-9DD1-D7E07D21E93F} = DAX
// For maximum compatibility we pass the query as plain text; modern MSOLAP
// determines the dialect from the query content.
ADODB::_RecordsetPtr spRs;
spRs.CreateInstance(__uuidof(ADODB::Recordset));
_variant_t vtConn(static_cast<IDispatch*>(ctx->spConn));
// Convert UTF-8 query to wide BSTR
int wlen = MultiByteToWideChar(CP_UTF8, 0, query, -1, nullptr, 0);
std::wstring wq(wlen, L'\0');
MultiByteToWideChar(CP_UTF8, 0, query, -1, &wq[0], wlen);
spRs->Open(_bstr_t(wq.c_str()), vtConn,
ADODB::adOpenForwardOnly,
ADODB::adLockReadOnly,
ADODB::adCmdText);
long fieldCount = spRs->Fields->Count;
// Collect column names
res->colNames.reserve(static_cast<size_t>(fieldCount));
for (long i = 0; i < fieldCount; ++i) {
ADODB::FieldPtr fld = spRs->Fields->GetItem(static_cast<long>(i));
res->colNames.push_back(bstr_to_utf8(fld->Name));
}
// Collect rows
while (!spRs->AdoEOF) {
std::vector<std::string> row;
row.reserve(static_cast<size_t>(fieldCount));
for (long i = 0; i < fieldCount; ++i) {
ADODB::FieldPtr fld = spRs->Fields->GetItem(static_cast<long>(i));
row.push_back(variant_to_string(_variant_t(fld->Value)));
}
res->rows.push_back(std::move(row));
spRs->MoveNext();
}
spRs->Close();
}
catch (_com_error& ce) {
std::string msg = "Query execution failed: ";
if (ce.Description().length() > 0)
msg += bstr_to_utf8(ce.Description());
else
msg += bstr_to_utf8(_bstr_t(ce.ErrorMessage()));
set_error(msg);
delete res;
return nullptr;
}
catch (...) {
set_error("Unknown exception during query execution.");
delete res;
return nullptr;
}
return static_cast<OLAP_RESULT>(res);
}
OLAP_API void olap_free_result(OLAP_RESULT result) {
if (result)
delete static_cast<OlapResult*>(result);
}
OLAP_API int olap_get_column_count(OLAP_RESULT result) {
if (!result) return -1;
return static_cast<int>(static_cast<OlapResult*>(result)->colNames.size());
}
OLAP_API long long olap_get_row_count(OLAP_RESULT result) {
if (!result) return -1LL;
return static_cast<long long>(static_cast<OlapResult*>(result)->rows.size());
}
OLAP_API const char* olap_get_column_name(OLAP_RESULT result, int col_index) {
if (!result) return nullptr;
auto* res = static_cast<OlapResult*>(result);
if (col_index < 0 || static_cast<size_t>(col_index) >= res->colNames.size())
return nullptr;
return res->colNames[static_cast<size_t>(col_index)].c_str();
}
OLAP_API const char* olap_get_value(OLAP_RESULT result, long long row_index, int col_index) {
if (!result) return nullptr;
auto* res = static_cast<OlapResult*>(result);
if (row_index < 0 || static_cast<size_t>(row_index) >= res->rows.size())
return nullptr;
const auto& row = res->rows[static_cast<size_t>(row_index)];
if (col_index < 0 || static_cast<size_t>(col_index) >= row.size())
return nullptr;
return row[static_cast<size_t>(col_index)].c_str();
}
OLAP_API const char* olap_get_last_error(void) {
return g_lastError.c_str();
}
OLAP_API const char* olap_get_version(void) {
return "1.0.0";
}
// ---------------------------------------------------------------------------
// DLL entry point
// ---------------------------------------------------------------------------
BOOL APIENTRY DllMain(HMODULE /*hModule*/, DWORD reason, LPVOID /*lpReserved*/) {
switch (reason) {
case DLL_PROCESS_ATTACH:
case DLL_PROCESS_DETACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}