-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathodbc_internal_commons.cc
More file actions
1383 lines (1297 loc) · 49.2 KB
/
Copy pathodbc_internal_commons.cc
File metadata and controls
1383 lines (1297 loc) · 49.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
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 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/odbc/bq_driver/internal/odbc_internal_commons.h"
#include "google/cloud/odbc/bq_client_interface/utils.h"
#include "google/cloud/odbc/bq_driver/internal/trace_utils.h"
#include "google/cloud/odbc/bq_driver/internal/utils.h"
#include <cmath>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
namespace google::cloud::odbc_bq_driver_internal {
using ::google::cloud::Options;
using ::google::cloud::bigquery_v2_minimal_internal::DatasetReference;
using ::google::cloud::bigquery_v2_minimal_internal::GetQueryResults;
using ::google::cloud::bigquery_v2_minimal_internal::Job;
using ::google::cloud::bigquery_v2_minimal_internal::JobCreationMode;
using ::google::cloud::bigquery_v2_minimal_internal::PostQueryRequest;
using ::google::cloud::bigquery_v2_minimal_internal::PostQueryResults;
using ::google::cloud::bigquery_v2_minimal_internal::QueryParameter;
using ::google::cloud::bigquery_v2_minimal_internal::QueryParameterType;
using ::google::cloud::bigquery_v2_minimal_internal::QueryParameterValue;
using ::google::cloud::bigquery_v2_minimal_internal::QueryRequest;
using ::google::cloud::bigquery_v2_minimal_internal::RowData;
using ::google::cloud::bigquery_v2_minimal_internal::TableFieldSchema;
#if (!defined(_WIN32) || defined(_WIN64)) && !defined(NO_ARROW)
using ::google::cloud::bigquery_v2_minimal_internal::TableReference;
#endif // (!defined(_WIN32) || defined(_WIN64)) && !defined(NO_ARROW)
using ::google::cloud::bigquery_v2_minimal_internal::TableSchema;
using google::cloud::odbc_bigquery_client_interface::MaxRetriesOption;
using ::google::cloud::odbc_internal::SQLStates;
using ::google::cloud::odbc_internal::StatusRecord;
using ::google::cloud::odbc_internal::StatusRecordOr;
using chrono_ms = std::chrono::milliseconds;
using json = nlohmann::json;
// Constants for Unix timestamp calculations
int const kSecondsPerDay = 86400;
int const kSecondsPerYear = 31536000;
int const kSecondsPerLeapYear = 31622400; // 366 days
int const kSecondsPerHour = 3600;
int const kSecondsPerMinute = 60;
constexpr int kMaxNumericPrecision = 38;
constexpr int kMaxNumericScale = 9;
// converting the given string to Numeric number
// getting scale ,precision, sign and the value from sting parameter
odbc_internal::StatusRecord GetNumericDetailsFromStr(
std::string const& src_dsval, SQL_NUMERIC_STRUCT& numst) {
SQLCHAR sign = 1;
SQLCHAR precision = 0;
SQLSCHAR scale;
std::string num_str;
int integral_count = 0;
int fractional_count = 0;
bool fractional_truncated = false;
auto status_record = odbc_internal::StatusRecord::Ok();
// Handle leading whitespace
size_t i = 0;
while (isspace(src_dsval[i])) {
i++;
}
// Check for sign
if (src_dsval[i] == '-') {
sign = 0;
i++;
}
// Extract digits before decimal point
while (isdigit(src_dsval[i])) {
char ch = src_dsval[i];
if (integral_count != 0 || ch != '0') {
num_str += ch;
}
integral_count++;
i++;
}
if (integral_count == 1 && num_str.empty()) {
num_str = "0";
}
// Find decimal point
if (src_dsval[i] == '.') {
i++;
}
// Extract digits after decimal point
while (isdigit(src_dsval[i])) {
if (fractional_count < kMaxNumericScale) {
num_str += src_dsval[i];
fractional_count++;
} else {
fractional_truncated = true;
}
i++;
}
if (integral_count == 1 && num_str[0] == '0' &&
num_str.find_first_not_of('0', 1) == std::string::npos) {
num_str = "0";
sign = 1;
fractional_count = 0;
fractional_truncated = false;
}
if (integral_count + fractional_count > kMaxNumericPrecision) {
LOG(ERROR) << "GetNumericDetailsFromStr::Numeric value out of range.";
return StatusRecord{SQLStates::k_22003(), "Numeric value out of range"};
}
// For NUmeric data type we have limited length defined by driver itself
// driver forces this limit by SQL_NUMERIC_STRUCT which has value of length
// SQL_MAX_NUMERIC_LEN i.e 16
if (integral_count >= SQL_MAX_NUMERIC_LEN) {
scale = 0;
precision = SQL_MAX_NUMERIC_LEN;
} else {
int maxlen = SQL_MAX_NUMERIC_LEN;
int limit_scale = maxlen - integral_count;
precision = integral_count + fractional_count;
scale = fractional_count;
if (scale >= limit_scale) scale = limit_scale;
if (precision >= SQL_MAX_NUMERIC_LEN) precision = SQL_MAX_NUMERIC_LEN;
}
if (fractional_truncated) {
LOG(WARNING) << "GetNumericDetailsFromStr::Fractional truncation (loss of "
"precision).";
status_record = StatusRecord{SQLStates::k_01S07(),
"Fractional truncation (loss of precision)"};
}
numst.scale = scale;
numst.precision = precision;
numst.sign = sign;
uint64_t dd = std::stoull(num_str);
memset(numst.val, 0, SQL_MAX_NUMERIC_LEN);
memcpy(numst.val, &dd, sizeof(dd));
return status_record;
}
bool IsLeapYear(int year) {
return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
}
int DaysInMonth(int year, int month) {
static int const kDaysInMonth[] = {31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31};
if (month == 2 && IsLeapYear(year)) {
return 29;
}
return kDaysInMonth[month - 1];
}
StatusRecord ConvertUnixTimestampToTimestampStruct(
double unix_timestamp, SQL_TIMESTAMP_STRUCT& timestamp_struct) {
// Check for invalid timestamp (e.g., negative or non-finite)
if (unix_timestamp < 0 || !std::isfinite(unix_timestamp)) {
LOG(ERROR)
<< "ConvertUnixTimestampToTimestampStruct::Invalid Unix timestamp: "
<< unix_timestamp;
return StatusRecord{SQLStates::k_01004(), "Invalid Unix timestamp"};
}
// Calculate whole seconds and fractional part
auto total_seconds = static_cast<time_t>(unix_timestamp);
int fractional_part =
round((unix_timestamp - total_seconds) * 1000000); // Microseconds
// Calculate the date and time components
int year = 1970;
while (total_seconds >=
(IsLeapYear(year) ? kSecondsPerLeapYear : kSecondsPerYear)) {
total_seconds -= (IsLeapYear(year) ? kSecondsPerLeapYear : kSecondsPerYear);
++year;
}
int month = 1;
while (total_seconds >= (DaysInMonth(year, month) * kSecondsPerDay)) {
total_seconds -= (DaysInMonth(year, month) * kSecondsPerDay);
++month;
}
int day = total_seconds / kSecondsPerDay + 1;
total_seconds %= kSecondsPerDay;
int hour = total_seconds / kSecondsPerHour;
total_seconds %= kSecondsPerHour;
int minute = total_seconds / kSecondsPerMinute;
total_seconds %= kSecondsPerMinute;
int second = total_seconds;
// Fill SQL_TIMESTAMP_STRUCT
timestamp_struct.year = static_cast<int16_t>(year);
timestamp_struct.month = static_cast<unsigned char>(month);
timestamp_struct.day = static_cast<unsigned char>(day);
timestamp_struct.hour = static_cast<unsigned char>(hour);
timestamp_struct.minute = static_cast<unsigned char>(minute);
timestamp_struct.second = static_cast<unsigned char>(second);
timestamp_struct.fraction = fractional_part;
return StatusRecord::Ok();
}
StatusRecordOr<SQL_DATE_STRUCT> ConvertStringToDateStruct(
std::string const& date_str) {
if (date_str.empty() || date_str.size() < SQL_DATE_LEN) {
LOG(ERROR) << "ConvertStringToDateStruct::Invalid date string format: "
<< date_str;
return StatusRecord{
SQLStates::k_HY000(),
"Invalid date string format: the string is either empty or too short."};
}
int year = std::stoi(date_str.substr(0, 4));
int month = std::stoi(date_str.substr(5, 2));
int day = std::stoi(date_str.substr(8, 2));
SQL_DATE_STRUCT date_struct;
date_struct.year = static_cast<SQLSMALLINT>(year);
date_struct.month = static_cast<SQLUSMALLINT>(month);
date_struct.day = static_cast<SQLUSMALLINT>(day);
return date_struct;
}
StatusRecord ConvertStringToIntervalStruct(
std::string const& interval_str, SQL_INTERVAL_STRUCT& interval_struct) {
if (interval_str.empty()) {
LOG(ERROR)
<< "ConvertStringToIntervalStruct::Interval string can't be empty.";
return StatusRecord{SQLStates::k_HY000(),
"Interval string can't be empty."};
}
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int fraction = 0;
int matched_items =
std::sscanf(interval_str.c_str(), "%d-%d %d %d:%d:%d.%d", &year, &month,
&day, &hour, &minute, &second, &fraction);
if (matched_items == 6) {
fraction = 0;
} else if (matched_items != 7) {
LOG(ERROR)
<< "ConvertStringToIntervalStruct::Invalid interval string format: "
<< interval_str;
return StatusRecord{SQLStates::k_HY000(), "Invalid interval string format"};
}
interval_struct.interval_sign =
(year < 0 || month < 0 || day < 0 || hour < 0 || minute < 0 || second < 0)
? -1
: 1;
if (year != 0 || month != 0) {
if (day == 0 && hour == 0 && minute == 0 && second == 0) {
if (year != 0 && month == 0) {
interval_struct.interval_type = SQL_IS_YEAR;
interval_struct.intval.year_month.year = static_cast<SQLUINTEGER>(year);
} else if (year == 0 && month != 0) {
interval_struct.interval_type = SQL_IS_MONTH;
interval_struct.intval.year_month.month =
static_cast<SQLUINTEGER>(month);
} else if (year != 0 && month != 0) {
interval_struct.interval_type = SQL_IS_YEAR_TO_MONTH;
interval_struct.intval.year_month.year = static_cast<SQLUINTEGER>(year);
interval_struct.intval.year_month.month =
static_cast<SQLUINTEGER>(month);
} else {
LOG(ERROR)
<< "ConvertStringToIntervalStruct::Invalid year-month interval.";
return StatusRecord{SQLStates::k_HY000(),
"Invalid year-month interval."};
}
} else {
LOG(ERROR) << "ConvertStringToIntervalStruct::Year-month interval must "
"not include day/time.";
return StatusRecord{SQLStates::k_HY000(),
"Year-month interval must not include day/time."};
}
} else if (day != 0 || hour != 0 || minute != 0 || second != 0) {
if (hour == 0 && minute == 0 && second == 0) {
interval_struct.interval_type = SQL_IS_DAY;
interval_struct.intval.day_second.day = static_cast<SQLUINTEGER>(day);
} else if (day == 0 && minute == 0 && second == 0) {
interval_struct.interval_type = SQL_IS_HOUR;
interval_struct.intval.day_second.hour = static_cast<SQLUINTEGER>(hour);
} else if (day == 0 && hour == 0 && second == 0) {
interval_struct.interval_type = SQL_IS_MINUTE;
interval_struct.intval.day_second.minute =
static_cast<SQLUINTEGER>(minute);
} else if (day == 0 && hour == 0 && minute == 0) {
interval_struct.interval_type = SQL_IS_SECOND;
interval_struct.intval.day_second.second =
static_cast<SQLUINTEGER>(second);
} else if (day != 0 && hour != 0 && minute == 0 && second == 0) {
interval_struct.interval_type = SQL_IS_DAY_TO_HOUR;
interval_struct.intval.day_second.day = static_cast<SQLUINTEGER>(day);
interval_struct.intval.day_second.hour = static_cast<SQLUINTEGER>(hour);
} else if (day != 0 && minute != 0 && second == 0) {
interval_struct.interval_type = SQL_IS_DAY_TO_MINUTE;
interval_struct.intval.day_second.day = static_cast<SQLUINTEGER>(day);
interval_struct.intval.day_second.hour = static_cast<SQLUINTEGER>(hour);
interval_struct.intval.day_second.minute =
static_cast<SQLUINTEGER>(minute);
} else if (day == 0 && hour != 0 && minute != 0 && second == 0) {
interval_struct.interval_type = SQL_IS_HOUR_TO_MINUTE;
interval_struct.intval.day_second.hour = static_cast<SQLUINTEGER>(hour);
interval_struct.intval.day_second.minute =
static_cast<SQLUINTEGER>(minute);
} else if (day == 0 && hour != 0 && second != 0) {
interval_struct.interval_type = SQL_IS_HOUR_TO_SECOND;
interval_struct.intval.day_second.hour = static_cast<SQLUINTEGER>(hour);
interval_struct.intval.day_second.minute =
static_cast<SQLUINTEGER>(minute);
interval_struct.intval.day_second.second =
static_cast<SQLUINTEGER>(second);
} else if (day == 0 && hour == 0 && minute != 0 && second != 0) {
interval_struct.interval_type = SQL_IS_MINUTE_TO_SECOND;
interval_struct.intval.day_second.minute =
static_cast<SQLUINTEGER>(minute);
interval_struct.intval.day_second.second =
static_cast<SQLUINTEGER>(second);
} else {
interval_struct.interval_type = SQL_IS_DAY_TO_SECOND;
interval_struct.intval.day_second.day = static_cast<SQLUINTEGER>(day);
interval_struct.intval.day_second.hour = static_cast<SQLUINTEGER>(hour);
interval_struct.intval.day_second.minute =
static_cast<SQLUINTEGER>(minute);
interval_struct.intval.day_second.second =
static_cast<SQLUINTEGER>(second);
}
}
return StatusRecord::Ok();
}
StatusRecordOr<std::string> FormatDateToString(SQL_DATE_STRUCT date) {
std::ostringstream oss;
oss << std::setfill('0');
oss << std::setw(4) << date.year << "-" << std::setw(2) << date.month << "-"
<< std::setw(2) << date.day;
return oss.str();
}
std::string FormatIntervalToString(const SQL_INTERVAL_STRUCT interval) {
char buffer[80];
switch (interval.interval_type) {
case SQL_IS_YEAR:
snprintf(buffer, sizeof(buffer), "%d-0 0 0:0:0",
interval.intval.year_month.year);
break;
case SQL_IS_MONTH:
snprintf(buffer, sizeof(buffer), "0-%d 0 0:0:0",
interval.intval.year_month.month);
break;
case SQL_IS_YEAR_TO_MONTH:
snprintf(buffer, sizeof(buffer), "%d-%d 0 0:0:0",
interval.intval.year_month.year,
interval.intval.year_month.month);
break;
case SQL_IS_DAY:
snprintf(buffer, sizeof(buffer), "0-0 %d 0:0:0",
interval.intval.day_second.day);
break;
case SQL_IS_HOUR:
snprintf(buffer, sizeof(buffer), "0-0 0 %d:0:0",
interval.intval.day_second.hour);
break;
case SQL_IS_MINUTE:
snprintf(buffer, sizeof(buffer), "0-0 0 0:%d:0",
interval.intval.day_second.minute);
break;
case SQL_IS_SECOND:
if (interval.intval.day_second.fraction != 0) {
snprintf(buffer, sizeof(buffer), "0-0 0 0:0:%d.%09d",
interval.intval.day_second.second,
interval.intval.day_second.fraction);
} else {
snprintf(buffer, sizeof(buffer), "0-0 0 0:0:%d",
interval.intval.day_second.second);
}
break;
case SQL_IS_DAY_TO_HOUR:
snprintf(buffer, sizeof(buffer), "0-0 %d %d:0:0",
interval.intval.day_second.day, interval.intval.day_second.hour);
break;
case SQL_IS_DAY_TO_MINUTE:
snprintf(buffer, sizeof(buffer), "0-0 %d %d:%d:0",
interval.intval.day_second.day, interval.intval.day_second.hour,
interval.intval.day_second.minute);
break;
case SQL_IS_DAY_TO_SECOND:
if (interval.intval.day_second.fraction != 0) {
snprintf(buffer, sizeof(buffer), "0-0 %d %d:%d:%d.%09d",
interval.intval.day_second.day,
interval.intval.day_second.hour,
interval.intval.day_second.minute,
interval.intval.day_second.second,
interval.intval.day_second.fraction);
} else {
snprintf(buffer, sizeof(buffer), "0-0 %d %d:%d:%d",
interval.intval.day_second.day,
interval.intval.day_second.hour,
interval.intval.day_second.minute,
interval.intval.day_second.second);
}
break;
case SQL_IS_HOUR_TO_MINUTE:
snprintf(buffer, sizeof(buffer), "0-0 0 %d:%d:0",
interval.intval.day_second.hour,
interval.intval.day_second.minute);
break;
case SQL_IS_HOUR_TO_SECOND:
if (interval.intval.day_second.fraction != 0) {
snprintf(buffer, sizeof(buffer), "0-0 0 %d:%d:%d.%09d",
interval.intval.day_second.hour,
interval.intval.day_second.minute,
interval.intval.day_second.second,
interval.intval.day_second.fraction);
} else {
snprintf(buffer, sizeof(buffer), "0-0 0 %d:%d:%d",
interval.intval.day_second.hour,
interval.intval.day_second.minute,
interval.intval.day_second.second);
}
break;
case SQL_IS_MINUTE_TO_SECOND:
if (interval.intval.day_second.fraction != 0) {
snprintf(buffer, sizeof(buffer), "0-0 0 0:%d:%d.%09d",
interval.intval.day_second.minute,
interval.intval.day_second.second,
interval.intval.day_second.fraction);
} else {
snprintf(buffer, sizeof(buffer), "0-0 0 0:%d:%d",
interval.intval.day_second.minute,
interval.intval.day_second.second);
}
break;
default:
snprintf(buffer, sizeof(buffer), "Unknown interval type");
break;
}
return std::string(buffer);
}
std::string FormatNumericToString(SQL_NUMERIC_STRUCT numeric) {
uint64_t value = 0;
for (int i = numeric.precision - 1; i >= 0; --i) {
value = (value << 8) + numeric.val[i];
}
std::string result = std::to_string(value);
if (numeric.scale > 0) {
if (result.length() <= numeric.scale) {
result =
"0." + std::string(numeric.scale - result.length(), '0') + result;
} else {
result.insert(result.length() - numeric.scale, ".");
}
}
if (numeric.sign == 0) {
result = "-" + result;
}
return result;
}
StatusRecordOr<SQL_TIMESTAMP_STRUCT> ConvertStringToTimestampStruct(
std::string const& date_str) {
std::string cleaned_date_str = date_str;
std::replace(cleaned_date_str.begin(), cleaned_date_str.end(), 'T', ' ');
SQL_TIMESTAMP_STRUCT date_struct = {};
int year;
int month;
int day;
int hour;
int minute;
int second;
char fraction_str[10] = "0";
int matched =
std::sscanf(cleaned_date_str.c_str(), "%4d-%2d-%2d %2d:%2d:%2d.%6s",
&year, &month, &day, &hour, &minute, &second, fraction_str);
if (matched < 6) {
LOG(ERROR) << "ConvertStringToTimestampStruct::sscanf:: String not "
"correctly converted to timestamp. Input: "
<< cleaned_date_str;
return StatusRecord{SQLStates::k_HY000(),
"String not correctly converted to timestamp"};
}
SQLUINTEGER fraction = 0;
if (matched == 7) {
int len = 0;
for (char ch : std::string(fraction_str)) {
if (!std::isdigit(ch)) {
LOG(ERROR) << "ConvertStringToTimestampStruct:: Fractional part is not "
"a valid number. Input: "
<< cleaned_date_str;
return StatusRecord{SQLStates::k_HY000(),
"Fractional part is not a valid number"};
}
fraction = fraction * 10 + (ch - '0');
++len;
}
for (; len < 6; ++len) {
fraction *= 10;
}
}
date_struct.year = static_cast<SQLSMALLINT>(year);
date_struct.month = static_cast<SQLUSMALLINT>(month);
date_struct.day = static_cast<SQLUSMALLINT>(day);
date_struct.hour = static_cast<SQLUSMALLINT>(hour);
date_struct.minute = static_cast<SQLUSMALLINT>(minute);
date_struct.second = static_cast<SQLUSMALLINT>(second);
date_struct.fraction = fraction;
return date_struct;
}
StatusRecordOr<ResultSet> ProcessResultSetRows(
TableSchema const& schema, std::vector<RowData> const& rows) {
ResultSet result_set;
// Populate the schema for each row. The row schema
// indicates how they should converted back for the application buffers in
// SQLFetch.
for (int i = 0; i < schema.fields.size(); i++) {
TableFieldSchema table_field_schema = schema.fields[i];
ColumnSchema col_schema;
col_schema.col_index = i;
StatusRecordOr<BQDataType> type_status_record =
ConvertDSType(table_field_schema.type);
if (!type_status_record.Ok()) {
LOG(ERROR) << "ProcessResultSetRows::ConvertDSType:: "
<< type_status_record.GetStatusRecord().message;
return type_status_record.GetStatusRecord();
}
col_schema.col_type = *type_status_record;
col_schema.is_mode_repeated = (table_field_schema.mode == "REPEATED");
result_set.row_schema.emplace_back(col_schema);
}
// Populate the data for each row.
for (auto const& row : rows) {
DSRow rs_row;
int i = 0;
for (auto const& col : row.columns) {
BQDataType col_type;
if (result_set.row_schema[i].is_mode_repeated)
col_type = kArray;
else
col_type = result_set.row_schema[i].col_type;
std::string data = col.value;
if (col.is_null) {
rs_row.emplace_back(kNullValue);
} else if (!data.empty()) {
DSValue row_val;
switch (col_type) {
case BQDataType::kNumeric:
case BQDataType::kBigNumeric: {
NumericToDSValue(data, row_val);
break;
}
case BQDataType::kString: {
StringToDSValue(data, row_val);
break;
}
case BQDataType::kInt64: {
SQLBIGINT l_data;
try {
l_data = std::stoll(data);
} catch (std::exception const& ex) {
return StatusRecord{SQLStates::k_HY000(),
"data cannot be parsed as long long"};
}
ArithmeticToDSValue<SQLBIGINT>(l_data, row_val);
break;
}
case BQDataType::kFloat64: {
SQLDOUBLE d_data;
try {
d_data = std::stod(data);
} catch (std::exception const& ex) {
return StatusRecord{SQLStates::k_HY000(),
"data cannot be parsed as double"};
}
ArithmeticToDSValue<SQLDOUBLE>(d_data, row_val);
break;
}
case BQDataType::kJson:
case BQDataType::kStruct: {
StringToDSValue(data, row_val);
break;
}
case BQDataType::kArray: {
BQDataType array_type = result_set.row_schema[i].col_type;
ArrayJsonToDSValue(data, row_val, array_type);
break;
}
case BQDataType::kDate: {
auto date_struct = ConvertStringToDateStruct(data);
if (!date_struct.Ok()) {
return date_struct.GetStatusRecord();
}
DateToDSValue(date_struct.GetValue(), row_val);
break;
}
case BQDataType::kTime: {
SQL_TIME_STRUCT t_data = ConvertToTimeStruct(data);
TimeToDSValue(t_data, row_val);
break;
}
case BQDataType::kTimeStamp: {
double unix_timestamp;
try {
unix_timestamp = std::stod(data);
} catch (std::exception const& ex) {
return StatusRecord{SQLStates::k_HY000(),
"data cannot be parsed as double"};
}
SQL_TIMESTAMP_STRUCT time_struct;
ConvertUnixTimestampToTimestampStruct(unix_timestamp, time_struct);
TimestampToDSValue(time_struct, row_val);
break;
}
case BQDataType::kInterval: {
StringToDSValue(data, row_val);
break;
}
case BQDataType::kDatetime: {
auto time_struct = ConvertStringToTimestampStruct(data);
if (!time_struct.Ok()) {
return time_struct.GetStatusRecord();
}
TimestampToDSValue(time_struct.GetValue(), row_val);
break;
}
case BQDataType::kBytes: {
StringToDSValue(data, row_val);
break;
}
case BQDataType::kBool: {
bool bool_val = false;
std::transform(data.begin(), data.end(), data.begin(), ::tolower);
if (data == "1" || data == "true" || data == "yes") {
bool_val = true;
} else if (data == "0" || data == "false" || data == "no") {
bool_val = false;
}
BooleanToDSValue(bool_val, row_val);
break;
}
case BQDataType::kGeography:
case BQDataType::kRange: {
StringToDSValue(data, row_val);
break;
}
default: {
return StatusRecord{SQLStates::k_HY000(),
"Invalid or unsupported col BQ data type"};
}
}
rs_row.emplace_back(row_val);
} else {
DSValue empty_value;
StringToDSValue("", empty_value);
rs_row.emplace_back(empty_value);
}
i++;
}
result_set.rows.emplace_back(rs_row);
}
return result_set;
}
StatusRecordOr<ResultSet> ProcessPostQueryResults(
PostQueryResults const& post_query_results) {
if (!post_query_results.job_complete) {
// If this method is being called then the assumption is PostQueryResults
// contains all the results which in turn means job_complete would be set to
// true.
LOG(ERROR) << "ProcessPostQueryResults:: Unexpected value for "
"job_complete: expecting true.";
return StatusRecord{
SQLStates::k_HY000(),
"Internal Error: Unexpected value for job_complete: expecting true"};
}
return ProcessResultSetRows(post_query_results.schema,
post_query_results.rows);
}
StatusRecordOr<ResultSet> ProcessGetQueryResults(
GetQueryResults const& get_query_results) {
if (!get_query_results.job_complete) {
// If this method is being called then the assumption is GetQueryResults
// contains all the results which in turn means job_complete would be set to
// true.
LOG(ERROR) << "ProcessGetQueryResults:: Unexpected value for job_complete: "
"expecting true.";
return StatusRecord{
SQLStates::k_HY000(),
"Internal Error: Unexpected value for job_complete: expecting true"};
}
return ProcessResultSetRows(get_query_results.schema, get_query_results.rows);
}
StatusRecordOr<ResultSet> ProcessQueryResults(DSResults const& query_results) {
// If the variant holds `ResultSet`(case of HT API), return it directly
if (absl::holds_alternative<ResultSet>(query_results.data_source_results)) {
return absl::get<ResultSet>(query_results.data_source_results);
}
if (absl::holds_alternative<PostQueryResults>(
query_results.data_source_results)) {
return ProcessPostQueryResults(
absl::get<PostQueryResults>(query_results.data_source_results));
}
if (absl::holds_alternative<GetQueryResults>(
query_results.data_source_results)) {
return ProcessGetQueryResults(
absl::get<GetQueryResults>(query_results.data_source_results));
}
LOG(ERROR) << "ProcessPostQueryResults:: Unexpected value for job_complete: "
"expecting true.";
return StatusRecord{SQLStates::k_HY000(), "Invalid query results object"};
}
StatusRecordOr<std::vector<RowData>> GetRowsResults(
DSResults const& query_results) {
if (absl::holds_alternative<PostQueryResults>(
query_results.data_source_results)) {
auto results =
absl::get<PostQueryResults>(query_results.data_source_results);
if (!results.job_complete) {
LOG(ERROR) << "GetRowsResults:: Unexpected value for job_complete in "
"PostQueryResults: expecting true.";
return StatusRecord{
SQLStates::k_HY000(),
"Internal Error: Unexpected value for job_complete: expecting true"};
}
return results.rows;
}
if (absl::holds_alternative<GetQueryResults>(
query_results.data_source_results)) {
auto results =
absl::get<GetQueryResults>(query_results.data_source_results);
if (!results.job_complete) {
LOG(ERROR) << "GetRowsResults:: Unexpected value for job_complete in "
"GetQueryResults: expecting true.";
return StatusRecord{
SQLStates::k_HY000(),
"Internal Error: Unexpected value for job_complete: expecting true"};
}
return results.rows;
}
LOG(ERROR) << "GetRowsResults:: Invalid query results object type.";
return StatusRecord{SQLStates::k_HY000(), "Invalid query results object"};
}
StatusRecordOr<Job> CancelBQJob(ConnectionHandle& conn_handle,
std::string const& job_id,
std::string const& location) {
// validate we have a job.
if (job_id.empty()) {
LOG(ERROR) << "CancelBQJob:: Invalid or empty job id.";
return StatusRecord{SQLStates::k_HY000(), "Invalid or empty job id"};
}
// Validate the connection handle.
if (!conn_handle.IsConnected()) {
LOG(ERROR) << "CancelBQJob:: Connection to the data source is broken.";
return StatusRecord{SQLStates::k_08S01(),
"Connection to the data source is broken"};
}
// Validate we have a bq client.
auto bq_client = conn_handle.GetClient();
if (!bq_client) {
LOG(ERROR) << "CancelBQJob:: Invalid or null BQ Client within the "
"connection handle.";
return StatusRecord{
SQLStates::k_HY000(),
"Invalid or null BQ Client within the connection handle"};
}
// validate we have a project_id.
std::string project_id = conn_handle.GetDsn().catalog;
if (project_id.empty()) {
LOG(ERROR)
<< "CancelBQJob:: Invalid or empty catalog in connection handle.";
return StatusRecord{SQLStates::k_HY000(),
"Invalid or empty catalog in connection handle"};
}
Options options;
options.set<MaxRetriesOption>(conn_handle.GetDsn().max_retries);
return bq_client->CancelJob(project_id, job_id, location, options);
}
StatusRecordOr<PostQueryResults> PostQueryWithoutResults(
std::shared_ptr<ODBCBQClient> const& bq_client,
PostQueryRequest const& post_query_request, Options const& options) {
if (!bq_client) {
LOG(ERROR)
<< "PostQueryWithoutResults:: Invalid or null BQ Client within the "
"connection handle.";
return StatusRecord{
SQLStates::k_HY000(),
"Invalid or null BQ Client within the connection handle"};
}
// For now , we use default options.
// We can set timeout here as needed later.
auto pq_status = bq_client->PostQuery(post_query_request, options);
if (!pq_status) {
LOG(ERROR) << "PostQueryWithoutResults::PostQuery:: "
<< pq_status.GetStatusRecord().message;
return pq_status.GetStatusRecord();
}
return pq_status;
}
StatusRecordOr<PostQueryResults> PostQueryWithoutResults(
ConnectionHandle& conn_handle, PostQueryRequest const& post_query_request) {
// Validate the connection handle.
if (!conn_handle.IsConnected()) {
LOG(ERROR)
<< "PostQueryWithoutResults:: Connection to the data source is broken.";
return StatusRecord{SQLStates::k_08S01(),
"Connection to the data source is broken"};
}
Options options;
options.set<MaxRetriesOption>(conn_handle.GetDsn().max_retries);
auto pq_status = PostQueryWithoutResults(conn_handle.GetClient(),
post_query_request, options);
if (!pq_status) {
return pq_status.GetStatusRecord();
}
if (!conn_handle.IsSessionStarted() &&
!pq_status->session_info.session_id.empty()) {
conn_handle.SetSessionId(pq_status->session_info.session_id);
}
return pq_status;
}
odbc_internal::StatusRecordOr<TableSchema> BuildTableSchemaFromRowSchema(
RowSchema& row_schema,
std::map<std::string, ColumnSchema> const& metadata_schema) {
if (row_schema.empty()) {
LOG(ERROR) << "BuildTableSchemaFromRowSchema:: Row schema is empty.";
return StatusRecord{SQLStates::k_HY000(),
"row schema should not be less than 0"};
}
std::unordered_map<int, std::string> index_to_name_map;
for (auto const& [col_name, col_schema] : metadata_schema) {
index_to_name_map[col_schema.col_index] = col_name;
}
// we need to sort row_schema by col_index in ascending order.
std::sort(row_schema.begin(), row_schema.end(),
[](ColumnSchema const& a, ColumnSchema const& b) {
return a.col_index < b.col_index;
});
TableSchema schema;
for (auto& row : row_schema) {
TableFieldSchema field;
auto it = index_to_name_map.find(row.col_index);
if (it == index_to_name_map.end()) {
LOG(ERROR)
<< "BuildTableSchemaFromRowSchema:: No matching col_index found: "
<< row.col_index;
return StatusRecord{
SQLStates::k_HY000(),
"No matching col_index found: " + std::to_string(row.col_index)};
}
field.name = it->second;
auto result = GetDataTypeInStr(row.col_type);
if (!result) {
LOG(ERROR) << "BuildTableSchemaFromRowSchema::GetDataTypeInStr:: "
<< result.GetStatusRecord().message;
return StatusRecord{SQLStates::k_HY000(),
result.GetStatusRecord().message};
}
field.type = *result;
field.mode = row.is_mode_repeated ? "REPEATED" : "NULLABLE";
schema.fields.push_back(std::move(field));
}
return schema;
}
StatusRecordOr<BQDataType> ConvertDSType(std::string const& type) {
if (type == "STRING") {
return BQDataType::kString;
}
if (type == "INTEGER" || type == "INT64") {
return BQDataType::kInt64;
}
if (type == "BOOL" || type == "BOOLEAN") {
return BQDataType::kBool;
}
if (type == "FLOAT64" || type == "FLOAT") {
return BQDataType::kFloat64;
}
if (type == "DECIMAL" || type == "NUMERIC") {
return BQDataType::kNumeric;
}
if (type == "BYTES") {
return BQDataType::kBytes;
}
if (type == "DATE") {
return BQDataType::kDate;
}
if (type == "DATETIME") {
return BQDataType::kDatetime;
}
if (type == "TIME") {
return BQDataType::kTime;
}
if (type == "TIMESTAMP") {
return BQDataType::kTimeStamp;
}
if (type == "BIGNUMERIC") {
return BQDataType::kBigNumeric;
}
if (type == "RANGE") {
return BQDataType::kRange;
}
if (type == "STRUCT" || type == "RECORD") {
return BQDataType::kStruct;
}
if (type == "JSON") {
return BQDataType::kJson;
}
if (type == "NULL") {
return BQDataType::kNull;
}
if (type == "INTERVAL") {
return BQDataType::kInterval;
}
if (type == "GEOGRAPHY") {
return BQDataType::kGeography;
}
if (type == "ARRAY") {
return BQDataType::kArray;
}
std::string err_msg = "Invalid Data Type: ";
err_msg.append(type);
LOG(ERROR) << "ConvertDSType:: " << err_msg;
return StatusRecord{SQLStates::k_HY000(), err_msg};
}
StatusRecordOr<QueryParameter> ConstructStringQueryParameter(
std::string const& parameter_name, std::string const& parameter_value) {
if (parameter_name.empty()) {
LOG(ERROR)
<< "ConstructStringQueryParameter:: Invalid (empty) parameter name.";
return StatusRecord{SQLStates::k_HY000(), "Invalid parameter name"};
}
QueryParameter query_param;
QueryParameterType query_param_type;
QueryParameterValue query_param_value;
query_param_type.type = "STRING";
query_param_value.value = parameter_value;
query_param.name = parameter_name;
query_param.parameter_type = query_param_type;
query_param.parameter_value = query_param_value;
return query_param;
}
StatusRecordOr<QueryParameter> ConstructStringArrayQueryParameter(
std::string const& parameter_name,
std::vector<std::string> const& parameter_values) {
if (parameter_name.empty()) {
LOG(ERROR) << "ConstructStringArrayQueryParameter:: Invalid (empty) "
"parameter name.";
return StatusRecord{SQLStates::k_HY000(), "Invalid parameter name"};
}
if (parameter_values.empty()) {