-
Notifications
You must be signed in to change notification settings - Fork 3
/
sybase_driver.hpp
1850 lines (1675 loc) · 67.5 KB
/
sybase_driver.hpp
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
/*
* File: sybase_driver.hpp
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef SYBASE_DRIVER_HPP
#define SYBASE_DRIVER_HPP
#include <ctpublic.h>
#include <cstring>
#include <vector>
#include <map>
#include <functional>
#include <algorithm>
#include <type_traits>
#include "driver.hpp"
namespace vgi { namespace dbconn { namespace dbd { namespace sybase {
static auto TRUE = CS_TRUE;
static auto FALSE = CS_FALSE;
using Locale = CS_LOCALE;
using Context = CS_CONTEXT;
using Connection = CS_CONNECTION;
using ServerMessage = CS_SERVERMSG;
using ClientMessage = CS_CLIENTMSG;
enum class cfg_type : char
{
CT_LIB,
CS_LIB
};
enum class action : CS_INT
{
SET = CS_SET,
GET = CS_GET,
CLEAR = CS_CLEAR,
SUPPORTED = CS_SUPPORTED // only used for connection properties
};
enum class debug_flag : CS_INT
{
ASYNC = CS_DBG_ASYNC,
ERROR = CS_DBG_ERROR,
MEM = CS_DBG_MEM,
API_STATES = CS_DBG_API_STATES,
NETWORK = CS_DBG_NETWORK,
API_LOGCALL = CS_DBG_API_LOGCALL,
ALL = CS_DBG_ALL,
PROTOCOL = CS_DBG_PROTOCOL,
PROTOCOL_STATES = CS_DBG_PROTOCOL_STATES,
DIAG = CS_DBG_DIAG
};
constexpr debug_flag operator|(debug_flag l, debug_flag r) { return debug_flag(utils::base_type(l) | utils::base_type(r)); }
// forward declaration
class driver;
class statement;
class connection;
//=====================================================================================
/**
* result_set - is a class that implements dbi::iresult_set interface and
* represents results of SQL query execution with collection of helper function
* to make the retrieval of the results of a query execution an easy task.
* result_set object cannot be instantiated directly, only via statement execute()
* function call. result_set objects automatically cancel executed
* queries and destroy allocated memory as they go out of scope.
*/
class result_set : public dbi::iresult_set
{
private:
struct column_data
{
CS_INT length = 0;
CS_SMALLINT indicator = 0;
std::vector<CS_CHAR> data;
void allocate(const size_t size)
{
data.resize(size);
std::memset(data.data(), 0, size);
}
operator char*()
{
return data.data();
}
};
public:
void clear()
{
columndata.clear();
name2index.clear();
row_cnt = 0;
affected_rows = 0;
more_res = false;
}
virtual bool has_data()
{
return (columns.size() > 0);
}
virtual bool more_results()
{
return more_res;
}
virtual size_t row_count() const
{
return std::abs(row_cnt);
}
virtual size_t rows_affected() const
{
return affected_rows;
}
virtual size_t column_count() const
{
return columns.size();
}
virtual std::string column_name(size_t col_idx)
{
if (col_idx >= columns.size())
throw std::runtime_error(std::string(__FUNCTION__).append(": Invalid column index"));
return columns[col_idx].name;
}
virtual int column_index(const std::string& col_name)
{
auto it = name2index.find(col_name);
if (it != name2index.end())
return it->second;
return -1;
}
virtual bool prev()
{
return scroll_fetch(CS_PREV);
}
virtual bool first()
{
return scroll_fetch(CS_FIRST);
}
virtual bool last()
{
return scroll_fetch(CS_LAST);
}
virtual bool next()
{
if (columndata.size() > 0)
{
if (scrollable)
{
return scroll_fetch(CS_NEXT);
}
else
{
if ((CS_SUCCEED == (retcode = ct_fetch(cscommand, CS_UNUSED, CS_UNUSED, CS_UNUSED, &result))) || CS_ROW_FAIL == retcode)
{
if (CS_ROW_FAIL == retcode)
throw std::runtime_error(std::string(__FUNCTION__).append(": Error fetching row ").append(std::to_string(result)));
row_cnt += result;
return true;
}
else
next_result();
}
}
return false;
}
virtual bool is_null(size_t col_idx)
{
if (col_idx >= columns.size())
throw std::runtime_error(std::string(__FUNCTION__).append(": Invalid column index"));
return (CS_NULLDATA == columndata[col_idx].indicator);
}
virtual int16_t get_short(size_t col_idx)
{
if (CS_TINYINT_TYPE == columns[col_idx].datatype)
return get<CS_TINYINT>(col_idx);
if (CS_SMALLINT_TYPE == columns[col_idx].datatype)
return get<CS_SMALLINT>(col_idx);
throw std::runtime_error(std::string(__FUNCTION__).append(": Invalid column data type (supported: tinyint, smallint)"));
}
virtual uint16_t get_ushort(size_t col_idx)
{
switch (columns[col_idx].datatype)
{
case CS_TINYINT_TYPE:
return get<CS_TINYINT>(col_idx);
case CS_USHORT_TYPE:
return get<CS_USHORT>(col_idx);
#ifdef CS_USMALLINT_TYPE
case CS_USMALLINT_TYPE:
return get<CS_USMALLINT>(col_idx);
#endif
default:
throw std::runtime_error(std::string(__FUNCTION__).append(": Invalid column data type (supported: tinyint, usmallint)"));
}
}
virtual int32_t get_int(size_t col_idx)
{
switch (columns[col_idx].datatype)
{
case CS_TINYINT_TYPE:
return get<CS_TINYINT>(col_idx);
case CS_SMALLINT_TYPE:
return get<CS_SMALLINT>(col_idx);
#ifdef CS_USMALLINT_TYPE
case CS_USMALLINT_TYPE:
return get<CS_USMALLINT>(col_idx);
#endif
case CS_INT_TYPE:
return get<CS_INT>(col_idx);
default:
throw std::runtime_error(std::string(__FUNCTION__).append(": Invalid column data type (supported: tinyint, smallint, usmallint, int)"));
}
}
virtual uint32_t get_uint(size_t col_idx)
{
switch (columns[col_idx].datatype)
{
case CS_TINYINT_TYPE:
return get<CS_TINYINT>(col_idx);
#ifdef CS_USMALLINT_TYPE
case CS_USMALLINT_TYPE:
return get<CS_USMALLINT>(col_idx);
#endif
case CS_USHORT_TYPE:
return get<CS_USHORT>(col_idx);
#ifdef CS_UINT_TYPE
case CS_UINT_TYPE:
return get<CS_UINT>(col_idx);
#endif
default:
throw std::runtime_error(std::string(__FUNCTION__).append(": Invalid column data type (supported: tinyint, usmallint, uint)"));
}
}
virtual int64_t get_long(size_t col_idx)
{
switch (columns[col_idx].datatype)
{
case CS_TINYINT_TYPE:
return get<CS_TINYINT>(col_idx);
case CS_SMALLINT_TYPE:
return get<CS_SMALLINT>(col_idx);
#ifdef CS_USMALLINT_TYPE
if (CS_USMALLINT_TYPE == columns[col_idx].datatype)
return get<CS_USMALLINT>(col_idx);
#endif
case CS_INT_TYPE:
return get<CS_INT>(col_idx);
#ifdef CS_UINT_TYPE
case CS_UINT_TYPE:
return get<CS_UINT>(col_idx);
#endif
case CS_LONG_TYPE:
return get<CS_LONG>(col_idx);
#ifdef CS_BIGINT_TYPE
case CS_BIGINT_TYPE:
return get<CS_BIGINT>(col_idx);
#endif
case CS_DECIMAL_TYPE:
case CS_NUMERIC_TYPE:
return get<int64_t>(col_idx);
default:
throw std::runtime_error(std::string(__FUNCTION__).append(": Invalid column data type (supported: tinyint, smallint, usmallint, int, uint, bigint)"));
}
}
virtual uint64_t get_ulong(size_t col_idx)
{
switch (columns[col_idx].datatype)
{
case CS_TINYINT_TYPE:
return get<CS_TINYINT>(col_idx);
#ifdef CS_USMALLINT_TYPE
case CS_USMALLINT_TYPE:
return get<CS_USMALLINT>(col_idx);
#endif
#ifdef CS_UINT_TYPE
case CS_UINT_TYPE:
return get<CS_UINT>(col_idx);
#endif
#ifdef CS_UBIGINT_TYPE
case CS_UBIGINT_TYPE:
return get<CS_UBIGINT>(col_idx);
#endif
case CS_DECIMAL_TYPE:
case CS_NUMERIC_TYPE:
return get<uint64_t>(col_idx);
default:
throw std::runtime_error(std::string(__FUNCTION__).append(": Invalid column data type (supported: tinyint, usmallint, uint, ubigint)"));
}
}
virtual float get_float(size_t col_idx)
{
if (CS_REAL_TYPE == columns[col_idx].datatype)
return get<CS_REAL>(col_idx);
if (CS_FLOAT_TYPE == columns[col_idx].datatype && columndata[col_idx].length <= 4)
return get<CS_FLOAT>(col_idx);
throw std::runtime_error(std::string(__FUNCTION__).append(": Invalid column data type (supported: real, float(p) if p < 16)"));
}
virtual double get_double(size_t col_idx)
{
switch (columns[col_idx].datatype)
{
case CS_REAL_TYPE:
return get<CS_REAL>(col_idx);
case CS_FLOAT_TYPE:
return get<CS_FLOAT>(col_idx);
case CS_MONEY_TYPE:
case CS_MONEY4_TYPE:
case CS_DECIMAL_TYPE:
case CS_NUMERIC_TYPE:
return get<double>(col_idx);
default:
throw std::runtime_error(std::string(__FUNCTION__).append(": Invalid column data type (supported: real, float, numeric/decimal)"));
}
}
virtual bool get_bool(size_t col_idx)
{
if (CS_BIT_TYPE != columns[col_idx].datatype)
throw std::runtime_error(std::string(__FUNCTION__).append(": Invalid column data type (supported: bit)"));
return get<bool>(col_idx);
}
virtual char get_char(size_t col_idx)
{
switch (columns[col_idx].datatype)
{
case CS_CHAR_TYPE:
case CS_LONGCHAR_TYPE:
case CS_TEXT_TYPE:
case CS_VARCHAR_TYPE:
case CS_BOUNDARY_TYPE:
case CS_SENSITIVITY_TYPE:
#ifdef CS_XML_TYPE
case CS_XML_TYPE:
#endif
break;
default:
throw std::runtime_error(std::string(__FUNCTION__).append(": Invalid column data type (supported: char, varchar, text)"));
}
return get<char>(col_idx);
}
virtual std::string get_string(size_t col_idx)
{
switch (columns[col_idx].datatype)
{
case CS_CHAR_TYPE:
case CS_LONGCHAR_TYPE:
case CS_TEXT_TYPE:
case CS_VARCHAR_TYPE:
case CS_BOUNDARY_TYPE:
case CS_SENSITIVITY_TYPE:
#ifdef CS_XML_TYPE
case CS_XML_TYPE:
#endif
break;
default:
throw std::runtime_error(std::string(__FUNCTION__).append(": Invalid column data type (supported: char, varchar, text)"));
}
return std::move(std::string((char*)columndata[col_idx], 0, columndata[col_idx].data.size()));
}
virtual int get_date(size_t col_idx)
{
#ifdef CS_TIME_TYPE
if (CS_TIME_TYPE == columns[col_idx].datatype)
throw std::runtime_error(std::string(__FUNCTION__).append(": Invalid column data type (supported: date, datetime, smalldatetime, bigdatetime)"));
#endif
#ifdef CS_BIGTIME_TYPE
if (CS_BIGTIME_TYPE == columns[col_idx].datatype)
throw std::runtime_error(std::string(__FUNCTION__).append(": Invalid column data type (supported: date, datetime, smalldatetime, bigdatetime)"));
#endif
getdt(col_idx);
return daterec.dateyear * 10000 + (daterec.datemonth + 1) * 100 + daterec.datedmonth;
}
virtual double get_time(size_t col_idx)
{
#ifdef CS_DATE_TYPE
if (CS_DATE_TYPE == columns[col_idx].datatype)
throw std::runtime_error(std::string(__FUNCTION__).append(": Invalid column data type (supported: time, datetime, smalldatetime, bigdatetime)"));
#endif
getdt(col_idx);
return (double)(daterec.datehour * 10000 + daterec.dateminute * 100 + daterec.datesecond) + (double)daterec.datemsecond / 1000.0;
}
virtual time_t get_datetime(size_t col_idx)
{
#ifdef CS_TIME_TYPE
if (CS_TIME_TYPE == columns[col_idx].datatype)
throw std::runtime_error(std::string(__FUNCTION__).append(": Invalid column data type (supported: date, datetime, smalldatetime, bigdatetime)"));
#endif
getdt(col_idx);
std::memset(&stm, 0, sizeof(stm));
stm.tm_sec = daterec.datesecond;
stm.tm_min = daterec.dateminute;
stm.tm_hour = daterec.datehour;
stm.tm_mon = daterec.datemonth;
stm.tm_mday = daterec.datedmonth;
stm.tm_year = daterec.dateyear - 1900;
stm.tm_isdst = -1;
return mktime(&stm);
}
virtual char16_t get_u16char(size_t col_idx)
{
switch (columns[col_idx].datatype)
{
case CS_UNICHAR_TYPE:
#ifdef CS_UNITEXT_TYPE
case CS_UNITEXT_TYPE:
#endif
break;
default:
throw std::runtime_error(std::string(__FUNCTION__).append(": Invalid column data type: ").append(std::to_string(columns[col_idx].datatype)));
}
return get<CS_UNICHAR>(col_idx);
}
virtual std::u16string get_u16string(size_t col_idx)
{
switch (columns[col_idx].datatype)
{
case CS_UNICHAR_TYPE:
#ifdef CS_UNITEXT_TYPE
case CS_UNITEXT_TYPE:
#endif
break;
default:
throw std::runtime_error(std::string(__FUNCTION__).append(": Invalid column data type: ").append(std::to_string(columns[col_idx].datatype)));
}
return std::move(std::u16string(reinterpret_cast<char16_t*>((char*)columndata[col_idx]), 0, columndata[col_idx].data.size() / sizeof(char16_t)));
}
virtual std::vector<uint8_t> get_binary(size_t col_idx)
{
switch (columns[col_idx].datatype)
{
case CS_IMAGE_TYPE:
case CS_BINARY_TYPE:
case CS_VARBINARY_TYPE:
case CS_LONGBINARY_TYPE:
#ifdef CS_BLOB_TYPE
case CS_BLOB_TYPE:
#endif
break;
default:
throw std::runtime_error(std::string(__FUNCTION__).append(": Invalid column data type: ").append(std::to_string(columns[col_idx].datatype)));
}
std::vector<uint8_t> t(columndata[col_idx].length);
std::memcpy(reinterpret_cast<void*>(t.data()), columndata[col_idx], columndata[col_idx].length);
return std::move(t);
}
bool cancel()
{
if (CS_SUCCEED != ct_cancel(nullptr, cscommand, CS_CANCEL_ALL))
return false;
return true;
}
private:
friend class statement;
result_set() {}
result_set(const result_set&) = delete;
result_set& operator=(const result_set&) = delete;
void set_scrollable(bool scroll)
{
scrollable = scroll;
}
bool next_result()
{
CS_INT res;
auto done = false;
auto failed_cnt = 0;
clear();
do_cancel = true;
while (false == done)
{
retcode = ct_results(cscommand, &res);
switch (retcode)
{
case CS_SUCCEED:
done = process_ct_result(res);
if (true == done)
{
if (true == has_data())
more_res = true;
else
done = false;
}
else if (CS_CMD_FAIL == res)
failed_cnt += 1;
break;
case CS_END_RESULTS:
case CS_CANCELED:
done = true;
break;
case CS_FAIL:
cancel();
throw std::runtime_error(std::string(__FUNCTION__).append(": Failed to get results"));
default:
cancel();
throw std::runtime_error(std::string(__FUNCTION__).append(": Failed ct_results returned unknown ret_code"));
}
}
if (failed_cnt > 0)
{
throw std::runtime_error(std::string(__FUNCTION__).append(": Failed to execute ").append(std::to_string(failed_cnt)).append(" command(s)"));
}
return more_res;
}
bool process_ct_result(CS_INT res)
{
switch (res)
{
case CS_PARAM_RESULT:
case CS_STATUS_RESULT:
case CS_ROW_RESULT:
case CS_CURSOR_RESULT:
process_result(false, true);
return true;
case CS_COMPUTE_RESULT:
process_result(true, true);
return true;
case CS_DESCRIBE_RESULT:
process_result(false, false);
break;
case CS_CMD_DONE:
if (CS_SUCCEED != ct_res_info(cscommand, CS_ROW_COUNT, &res, CS_UNUSED, nullptr))
throw std::runtime_error(std::string(__FUNCTION__).append(": Failed to get result row count"));
affected_rows += res > 0 ? res : 0;
break;
case CS_ROWFMT_RESULT: // not supported. seen only when the CS_EXPOSE_FORMATS property is enabled
case CS_COMPUTEFMT_RESULT:// not supported. seen only when the CS_EXPOSE_FORMATS property is enabled
case CS_MSG_RESULT: // not supported
break;
case CS_CMD_SUCCEED:
break;
case CS_CMD_FAIL:
break;
default:
throw std::runtime_error(std::string(__FUNCTION__).append(": Unknown return from ct_results: ").append(std::to_string(res)));
}
return false;
}
void process_result(bool compute, bool bind)
{
auto colcnt = 0;
if (CS_SUCCEED != ct_res_info(cscommand, CS_NUMDATA, &colcnt, CS_UNUSED, nullptr))
throw std::runtime_error(std::string(__FUNCTION__).append(": Failed to get number of columns"));
if (colcnt <= 0)
throw std::runtime_error(std::string(__FUNCTION__).append(": Returned zero columns"));
std::vector<std::string> colnames;
if (compute)
{
for (auto& dfmt : columns)
colnames.push_back(dfmt.name);
}
columns.resize(colcnt);
columndata.resize(colcnt);
auto agg_op = 0;
auto col_id = 0;
for (auto i = 0; i < colcnt; ++i)
{
std::memset(&columns[i], 0, sizeof(CS_DATAFMT));
if (CS_SUCCEED != ct_describe(cscommand, i + 1, &(columns[i])))
throw std::runtime_error(std::string(__FUNCTION__).append(": Failed to get column description: index ").append(std::to_string(i)));
if (compute)
{
if (CS_SUCCEED != ct_compute_info(cscommand, CS_COMP_OP, i + 1, &agg_op, CS_UNUSED, &(columns[i].namelen)))
throw std::runtime_error(std::string(__FUNCTION__).append(": Failed compute info call for operation"));
if (CS_SUCCEED != ct_compute_info(cscommand, CS_COMP_COLID, i + 1, &col_id, CS_UNUSED, &(columns[i].namelen)))
throw std::runtime_error(std::string(__FUNCTION__).append(": Failed compute info call for column id"));
col_id -= 1;
switch (agg_op)
{
case CS_OP_SUM: std::sprintf(columns[i].name, "sum(%s)", colnames[col_id].c_str()); break;
case CS_OP_AVG: std::sprintf(columns[i].name, "avg(%s)", colnames[col_id].c_str()); break;
case CS_OP_COUNT: std::sprintf(columns[i].name, "count(%s)", colnames[col_id].c_str()); break;
case CS_OP_MIN: std::sprintf(columns[i].name, "min(%s)", colnames[col_id].c_str()); break;
case CS_OP_MAX: std::sprintf(columns[i].name, "max(%s)", colnames[col_id].c_str()); break;
default: std::sprintf(columns[i].name, "unknown(%s)", colnames[col_id].c_str()); break;
}
}
else if (::strlen(columns[i].name) == 0)
std::sprintf(columns[i].name, "column%d", i + 1);
name2index[columns[i].name] = i;
columndata[i].allocate(columns[i].maxlength);
if (bind)
{
if (CS_SUCCEED != ct_bind(cscommand, i + 1, &(columns[i]), columndata[i], &(columndata[i].length), &(columndata[i].indicator)))
throw std::runtime_error(std::string(__FUNCTION__).append(": Failed to bind column ").append(std::to_string(i)));
}
}
}
bool scroll_fetch(CS_INT type)
{
if (scrollable)
{
switch (ct_scroll_fetch(cscommand, type, CS_UNUSED, CS_TRUE, &result))
{
case CS_END_DATA:
case CS_CURSOR_BEFORE_FIRST:
row_cnt = 0;
return false;
case CS_CURSOR_AFTER_LAST:
row_cnt += 1;
return false;
}
switch (type)
{
case CS_FIRST: row_cnt = 1; break;
case CS_LAST: row_cnt = -1; break;
case CS_PREV: row_cnt -= 1; break;
case CS_NEXT: row_cnt += 1; break;
}
return true;
}
else
throw std::runtime_error(std::string(__FUNCTION__).append(": The function can only be called if scrollable cursor is used "));
}
template<typename T>
T get(size_t col_idx)
{
if (is_null(col_idx))
throw std::runtime_error(std::string(__FUNCTION__).append(": Can't convert NULL data"));
switch (columns[col_idx].datatype)
{
case CS_NUMERIC_TYPE:
case CS_DECIMAL_TYPE:
case CS_MONEY_TYPE:
case CS_MONEY4_TYPE:
{
double num = 0.0;
std::memset(&destfmt, 0, sizeof(destfmt));
destfmt.maxlength = sizeof(num);
destfmt.datatype = CS_FLOAT_TYPE;
destfmt.format = CS_FMT_UNUSED;
destfmt.locale = nullptr;
if (CS_SUCCEED != cs_convert(cscontext, &columns[col_idx], static_cast<CS_VOID*>(columndata[col_idx]), &destfmt, &num, 0))
throw std::runtime_error(std::string(__FUNCTION__).append(": cs_convert failed"));
return num;
}
}
if (sizeof(T) < columndata[col_idx].data.size())
throw std::runtime_error(std::string(__FUNCTION__).append(": Sybase data type is larger than the primitive data type"));
return *(reinterpret_cast<T*>((char*)columndata[col_idx]));
}
void getdt(size_t col_idx)
{
if (is_null(col_idx))
throw std::runtime_error(std::string(__FUNCTION__).append(": Can't convert NULL data"));
switch (columns[col_idx].datatype)
{
case CS_DATETIME_TYPE:
case CS_DATETIME4_TYPE:
#ifdef CS_DATE_TYPE
case CS_DATE_TYPE:
#endif
#ifdef CS_TIME_TYPE
case CS_TIME_TYPE:
#endif
#ifdef CS_BIGDATETIME_TYPE
case CS_BIGDATETIME_TYPE:
#endif
#ifdef CS_BIGTIME_TYPE
case CS_BIGTIME_TYPE:
#endif
break;
default:
throw std::runtime_error(std::string(__FUNCTION__).append(": Invalid column data type (supported: date, time, datetime, smalldatetime, bigdatetime)"));
}
std::memset(&daterec, 0, sizeof(daterec));
if (CS_SUCCEED != cs_dt_crack(cscontext, columns[col_idx].datatype, static_cast<CS_VOID*>(columndata[col_idx]), &daterec))
throw std::runtime_error(std::string(__FUNCTION__).append(": cs_dt_crack failed"));
}
private:
bool scrollable = false;
bool do_cancel = false;
long row_cnt = 0;
size_t affected_rows = 0;
bool more_res = false;
Context* cscontext = nullptr;
CS_COMMAND* cscommand = nullptr;
CS_RETCODE retcode;
CS_INT result;
CS_DATAFMT destfmt;
CS_DATEREC daterec;
struct tm stm;
std::map<std::string, int> name2index;
std::vector<CS_DATAFMT> columns;
std::vector<column_data> columndata;
}; // result_set
//=====================================================================================
/**
* connection - is a class that implements dbi::iconnection interface and
* represents native database connection handle, in case of Sybase it's a C++
* wrap around around CS_CONTEXT and CS_CONNECTION.
* connection object cannot be instantiated directly, only via driver
* get_connection() function call. connection objects automatically delete the
* native connection handle they manage as soon as they themselves are destroyed.
*/
class connection : public dbi::iconnection
{
public:
virtual ~connection()
{
destroy();
}
connection(connection&& conn)
: ase(conn.ase), is_autocommit(conn.is_autocommit),
cscontext(conn.cscontext), csconnection(conn.csconnection),
server(std::move(conn.server)), user(std::move(conn.user)),
passwd(std::move(conn.passwd))
{
conn.cscontext = nullptr;
conn.csconnection = nullptr;
}
connection& operator=(connection&& conn)
{
if (this != &conn)
{
destroy();
ase = conn.ase;
is_autocommit = conn.is_autocommit;
cscontext = conn.cscontext;
csconnection = conn.csconnection;
conn.cscontext = nullptr;
conn.csconnection = nullptr;
server = std::move(conn.server);
user = std::move(conn.user);
passwd = std::move(conn.passwd);
}
return *this;
}
virtual bool connect()
{
if (true == connected())
disconnect();
if (nullptr != csconnection && CS_SUCCEED == ct_connect(csconnection, (server.empty() ? nullptr : const_cast<CS_CHAR*>(server.c_str())), server.empty() ? 0 : CS_NULLTERM))
is_server_ase();
return alive();
}
virtual void disconnect()
{
if (nullptr != csconnection)
{
CS_INT stat = 0;
ct_con_props(csconnection, CS_GET, CS_CON_STATUS, &stat, CS_UNUSED, nullptr);
if (CS_CONSTAT_DEAD == stat)
ct_close(csconnection, CS_FORCE_CLOSE);
else if (CS_CONSTAT_CONNECTED == stat)
{
ct_cancel(csconnection, nullptr, CS_CANCEL_ALL);
if (CS_SUCCEED != ct_close(csconnection, CS_UNUSED))
ct_close(csconnection, CS_FORCE_CLOSE);
}
}
};
virtual bool connected() const
{
if (nullptr != csconnection)
{
CS_INT stat = 0;
ct_con_props(csconnection, CS_GET, CS_CON_STATUS, &stat, CS_UNUSED, nullptr);
return (CS_CONSTAT_CONNECTED == stat || CS_CONSTAT_DEAD == stat);
}
return false;
}
virtual bool alive() const
{
if (nullptr != csconnection)
{
CS_INT stat = 0;
ct_con_props(csconnection, CS_GET, CS_CON_STATUS, &stat, CS_UNUSED, nullptr);
return (CS_CONSTAT_CONNECTED == stat);
}
return false;
}
virtual void autocommit(bool ac)
{
if (nullptr != csconnection)
{
CS_BOOL val = (ac ? TRUE : FALSE);
if (val != is_autocommit)
{
is_autocommit = val;
std::unique_ptr<dbi::istatement> stmt(get_statement(*this));
if (val)
stmt->execute("rollback tran");
else
stmt->execute("begin tran");
}
}
}
virtual void commit()
{
if (FALSE == is_autocommit)
{
std::unique_ptr<dbi::istatement> stmt(get_statement(*this));
stmt->execute("commit tran begin tran");
}
}
virtual void rollback()
{
if (FALSE == is_autocommit)
{
std::unique_ptr<dbi::istatement> stmt(get_statement(*this));
stmt->execute("rollback tran begin tran");
}
}
virtual dbi::istatement* get_statement(dbi::iconnection& iconn);
template<typename T>
connection& userdata(T& user_struct)
{
T* us = &user_struct;
if (nullptr == csconnection || CS_SUCCEED != ct_con_props(csconnection, CS_SET, CS_USERDATA, reinterpret_cast<CS_VOID*>(&us), sizeof(us), nullptr))
throw std::runtime_error(std::string(__FUNCTION__).append(": Failed to set connection user data pointer"));
return *this;
}
template<typename T>
connection& userdata(T*& user_struct)
{
auto len = 0;
if (nullptr == csconnection || CS_SUCCEED != ct_con_props(csconnection, CS_GET, CS_USERDATA, reinterpret_cast<CS_VOID*>(&user_struct), sizeof(user_struct), &len))
throw std::runtime_error(std::string(__FUNCTION__).append(": Failed to get connection user data pointer"));
return *this;
}
connection& props(action actn, CS_INT property, CS_VOID* buffer, CS_INT buflen = CS_UNUSED, CS_INT* outlen = nullptr)
{
if (nullptr == csconnection || nullptr == buffer || CS_SUCCEED != ct_con_props(csconnection, utils::base_type(actn), property, buffer, buflen, outlen))
throw std::runtime_error(std::string(__FUNCTION__).append(": Failed to set connection property"));
return *this;
}
Context* native_context() const
{
return cscontext;
}
Connection* native_connection() const
{
return csconnection;
}
bool is_ase()
{
return ase;
}
private:
friend class driver;
friend class statement;
connection() = delete;
connection(const connection&) = delete;
connection& operator=(const connection&) = delete;
connection(Context* context, CS_INT dbg_flag, const std::string& protofile, const std::string& server, const std::string& user, const std::string& passwd)
: cscontext(context), server(server), user(user), passwd(passwd)
{
if (CS_SUCCEED != ct_con_alloc(cscontext, &csconnection))
throw std::runtime_error(std::string(__FUNCTION__).append(": Failed to allocate connection struct"));
if (CS_SUCCEED != ct_con_props(csconnection, CS_SET, CS_USERNAME, const_cast<CS_CHAR*>(user.c_str()), CS_NULLTERM, nullptr))
throw std::runtime_error(std::string(__FUNCTION__).append(": Failed to set connection user"));
if (CS_SUCCEED != ct_con_props(csconnection, CS_SET, CS_PASSWORD, const_cast<CS_CHAR*>(passwd.c_str()), CS_NULLTERM, nullptr))
throw std::runtime_error(std::string(__FUNCTION__).append(": Failed to set connection password"));
if (false == protofile.empty() && CS_SUCCEED != ct_debug(nullptr, csconnection, CS_SET_PROTOCOL_FILE, CS_UNUSED, const_cast<CS_CHAR*>(protofile.c_str()), protofile.length()))
throw std::runtime_error(std::string(__FUNCTION__).append(": Failed to set debug protocol file name"));
if (0 != dbg_flag && CS_SUCCEED != ct_debug(cscontext, csconnection, CS_SET_FLAG, dbg_flag, nullptr, CS_UNUSED))
throw std::runtime_error(std::string(__FUNCTION__).append(": Failed to set debug flags"));
}
void destroy()
{
disconnect();
if (nullptr != csconnection)
{
ct_con_drop(csconnection);
csconnection = nullptr;
}
cscontext = nullptr;
}
void is_server_ase()
{
std::unique_ptr<dbi::istatement> stmt(get_statement(*this));
dbi::iresult_set* rs = stmt->execute("if object_id('dbo.sysobjects') is not null and object_id('dbo.syscolumns') is not null select 1 else select 0");
if (!rs->next())
throw std::runtime_error(std::string(__FUNCTION__).append(": Failed to get server type"));
ase = rs->get_int(0);
}
private:
bool ase = false;
CS_BOOL is_autocommit = CS_TRUE;
Context* cscontext = nullptr;
Connection* csconnection = nullptr;
std::string server;
std::string user;
std::string passwd;
};
//=====================================================================================
/**
* sybase ASE driver class based on ctlib sybase C library. This class cannot be
* used directly and is intended to be used via wrapper dbd::driver class
*/
class driver : public idriver
{
public:
~driver()
{
if (cslocale != nullptr && cscontext != nullptr)
cs_loc_drop(cscontext, cslocale);
destroy(cscontext);
}
dbi::connection get_connection(const std::string& server, const std::string& user = "", const std::string& passwd = "")
{
return create_connection(new connection(cscontext, dbg_flag, protofile, server, user, passwd));
}
driver& debug(debug_flag flag)