-
Notifications
You must be signed in to change notification settings - Fork 199
Expand file tree
/
Copy pathSnowflakeUtil.java
More file actions
1082 lines (981 loc) · 37.5 KB
/
Copy pathSnowflakeUtil.java
File metadata and controls
1082 lines (981 loc) · 37.5 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
package net.snowflake.client.internal.jdbc;
import static java.util.Arrays.stream;
import static net.snowflake.client.api.resultset.SnowflakeType.GEOGRAPHY;
import static net.snowflake.client.internal.core.Constants.OAUTH_ACCESS_TOKEN_EXPIRED_GS_CODE;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Types;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import net.snowflake.client.api.exception.ErrorCode;
import net.snowflake.client.api.exception.SnowflakeSQLException;
import net.snowflake.client.api.resultset.FieldMetadata;
import net.snowflake.client.api.resultset.SnowflakeType;
import net.snowflake.client.internal.api.implementation.resultset.FieldMetadataImpl;
import net.snowflake.client.internal.core.Constants;
import net.snowflake.client.internal.core.HttpClientSettingsKey;
import net.snowflake.client.internal.core.OCSPMode;
import net.snowflake.client.internal.core.ObjectMapperFactory;
import net.snowflake.client.internal.core.SFBaseSession;
import net.snowflake.client.internal.core.SFException;
import net.snowflake.client.internal.core.SFSessionProperty;
import net.snowflake.client.internal.exception.SnowflakeSQLLoggedException;
import net.snowflake.client.internal.jdbc.util.SnowflakeTypeUtil;
import net.snowflake.client.internal.log.SFLogger;
import net.snowflake.client.internal.log.SFLoggerFactory;
import net.snowflake.client.internal.util.ThrowingCallable;
import net.snowflake.common.core.SqlState;
import net.snowflake.common.util.ClassUtil;
import net.snowflake.common.util.FixedViewColumn;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
public class SnowflakeUtil {
private static final SFLogger logger = SFLoggerFactory.getLogger(SnowflakeUtil.class);
private static final ObjectMapper OBJECT_MAPPER = ObjectMapperFactory.getObjectMapper();
private static final Set<PosixFilePermission> directoryOwnerOnlyPermission =
PosixFilePermissions.fromString("rwx------");
// reauthenticate
private static final int ID_TOKEN_EXPIRED_GS_CODE = 390110;
private static final int SESSION_NOT_EXIST_GS_CODE = 390111;
private static final int MASTER_TOKEN_NOTFOUND = 390113;
private static final int MASTER_EXPIRED_GS_CODE = 390114;
private static final int MASTER_TOKEN_INVALID_GS_CODE = 390115;
private static final int ID_TOKEN_INVALID_LOGIN_REQUEST_GS_CODE = 390195;
public static final String BIG_DECIMAL_STR = "big decimal";
public static final String FLOAT_STR = "float";
public static final String DOUBLE_STR = "double";
public static final String DURATION_STR = "duration";
public static final String BOOLEAN_STR = "boolean";
public static final String SHORT_STR = "short";
public static final String INT_STR = "int";
public static final String LONG_STR = "long";
public static final String PERIOD_STR = "period";
public static final String TIME_STR = "time";
public static final String TIMESTAMP_STR = "timestamp";
public static final String DATE_STR = "date";
public static final String BYTE_STR = "byte";
public static final String BYTES_STR = "byte array";
public static String mapJson(Object ob) throws JsonProcessingException {
return OBJECT_MAPPER.writeValueAsString(ob);
}
public static void checkErrorAndThrowExceptionIncludingReauth(JsonNode rootNode)
throws SnowflakeSQLException {
checkErrorAndThrowExceptionSub(rootNode, true);
}
public static void checkErrorAndThrowException(JsonNode rootNode) throws SnowflakeSQLException {
checkErrorAndThrowExceptionSub(rootNode, false);
}
public static long getEpochTimeInMicroSeconds() {
Instant timestamp = Instant.now();
long micros =
TimeUnit.SECONDS.toMicros(timestamp.getEpochSecond())
+ TimeUnit.NANOSECONDS.toMicros(timestamp.getNano());
return micros;
}
/**
* Check the error in the JSON node and generate an exception based on information extracted from
* the node.
*
* @param rootNode json object contains error information
* @param raiseReauthenticateError raises SnowflakeReauthenticationRequest if true
* @throws SnowflakeSQLException the exception get from the error in the json
*/
private static void checkErrorAndThrowExceptionSub(
JsonNode rootNode, boolean raiseReauthenticateError) throws SnowflakeSQLException {
// no need to throw exception if success
if (rootNode.path("success").asBoolean()) {
return;
}
String errorMessage;
String sqlState;
int errorCode;
String queryId = "unknown";
// if we have sqlstate in data, it's a sql error
if (!rootNode.path("data").path("sqlState").isMissingNode()) {
sqlState = rootNode.path("data").path("sqlState").asText();
errorCode = rootNode.path("data").path("errorCode").asInt();
queryId = rootNode.path("data").path("queryId").asText();
errorMessage = rootNode.path("message").asText();
} else {
sqlState = SqlState.INTERNAL_ERROR; // use internal error sql state
// check if there is an error code in the envelope
if (!rootNode.path("code").isMissingNode()) {
errorCode = rootNode.path("code").asInt();
errorMessage = rootNode.path("message").asText();
} else {
errorCode = ErrorCode.INTERNAL_ERROR.getMessageCode();
errorMessage = "no_error_code_from_server";
try (PrintWriter writer = new PrintWriter("output.json", "UTF-8")) {
writer.print(rootNode.toString());
} catch (Exception ex) {
logger.debug("{}", ex);
}
}
}
if (raiseReauthenticateError) {
switch (errorCode) {
case ID_TOKEN_EXPIRED_GS_CODE:
case SESSION_NOT_EXIST_GS_CODE:
case MASTER_TOKEN_NOTFOUND:
case MASTER_EXPIRED_GS_CODE:
case MASTER_TOKEN_INVALID_GS_CODE:
case ID_TOKEN_INVALID_LOGIN_REQUEST_GS_CODE:
case OAUTH_ACCESS_TOKEN_EXPIRED_GS_CODE:
throw new SnowflakeReauthenticationRequest(queryId, errorMessage, sqlState, errorCode);
}
}
throw new SnowflakeSQLException(queryId, errorMessage, sqlState, errorCode);
}
/**
* This method should only be used internally
*
* @param colNode JsonNode
* @param jdbcTreatDecimalAsInt true if should treat Decimal as Int
* @param session SFBaseSession
* @return SnowflakeColumnMetadata
* @throws SnowflakeSQLException if an error occurs
*/
@Deprecated
public static SnowflakeColumnMetadata extractColumnMetadata(
JsonNode colNode, boolean jdbcTreatDecimalAsInt, SFBaseSession session)
throws SnowflakeSQLException {
return new SnowflakeColumnMetadata(colNode, jdbcTreatDecimalAsInt, session);
}
static ColumnTypeInfo getSnowflakeType(
String internalColTypeName,
String extColTypeName,
JsonNode udtOutputType,
SFBaseSession session,
int fixedColType,
boolean isStructuredType,
boolean isVectorType)
throws SnowflakeSQLLoggedException {
SnowflakeType baseType = SnowflakeTypeUtil.fromStringOrNull(internalColTypeName);
if (baseType == null) {
// Unknown Snowflake type (e.g. UUID) — report as OTHER with the actual type name
return new ColumnTypeInfo(
Types.OTHER,
defaultIfNull(extColTypeName, internalColTypeName.toUpperCase(Locale.ROOT)),
SnowflakeType.ANY);
}
ColumnTypeInfo columnTypeInfo;
switch (baseType) {
case TEXT:
columnTypeInfo =
new ColumnTypeInfo(Types.VARCHAR, defaultIfNull(extColTypeName, "VARCHAR"), baseType);
break;
case CHAR:
columnTypeInfo =
new ColumnTypeInfo(Types.CHAR, defaultIfNull(extColTypeName, "CHAR"), baseType);
break;
case INTEGER:
columnTypeInfo =
new ColumnTypeInfo(Types.INTEGER, defaultIfNull(extColTypeName, "INTEGER"), baseType);
break;
case DECFLOAT:
columnTypeInfo = new ColumnTypeInfo(Types.DECIMAL, "DECFLOAT", baseType);
break;
case FIXED:
if (isVectorType) {
columnTypeInfo =
new ColumnTypeInfo(Types.INTEGER, defaultIfNull(extColTypeName, "INTEGER"), baseType);
} else {
columnTypeInfo =
new ColumnTypeInfo(fixedColType, defaultIfNull(extColTypeName, "NUMBER"), baseType);
}
break;
case REAL:
if (isVectorType) {
columnTypeInfo =
new ColumnTypeInfo(Types.FLOAT, defaultIfNull(extColTypeName, "FLOAT"), baseType);
} else {
columnTypeInfo =
new ColumnTypeInfo(Types.DOUBLE, defaultIfNull(extColTypeName, "DOUBLE"), baseType);
}
break;
case TIMESTAMP:
case TIMESTAMP_LTZ:
columnTypeInfo =
new ColumnTypeInfo(
SnowflakeType.EXTRA_TYPES_TIMESTAMP_LTZ,
defaultIfNull(extColTypeName, "TIMESTAMPLTZ"),
baseType);
break;
case INTERVAL_YEAR_MONTH:
columnTypeInfo =
new ColumnTypeInfo(
SnowflakeType.EXTRA_TYPES_YEAR_MONTH_INTERVAL,
defaultIfNull(extColTypeName, "INTERVAL_YEAR_MONTH"),
baseType);
break;
case INTERVAL_DAY_TIME:
columnTypeInfo =
new ColumnTypeInfo(
SnowflakeType.EXTRA_TYPES_DAY_TIME_INTERVAL,
defaultIfNull(extColTypeName, "INTERVAL_DAY_TIME"),
baseType);
break;
case TIMESTAMP_NTZ:
// if the column type is changed to EXTRA_TYPES_TIMESTAMP_NTZ, update also JsonSqlInput
columnTypeInfo =
new ColumnTypeInfo(
Types.TIMESTAMP, defaultIfNull(extColTypeName, "TIMESTAMPNTZ"), baseType);
break;
case TIMESTAMP_TZ:
columnTypeInfo =
new ColumnTypeInfo(
SnowflakeType.EXTRA_TYPES_TIMESTAMP_TZ,
defaultIfNull(extColTypeName, "TIMESTAMPTZ"),
baseType);
break;
case DATE:
columnTypeInfo =
new ColumnTypeInfo(Types.DATE, defaultIfNull(extColTypeName, "DATE"), baseType);
break;
case TIME:
columnTypeInfo =
new ColumnTypeInfo(Types.TIME, defaultIfNull(extColTypeName, "TIME"), baseType);
break;
case BOOLEAN:
columnTypeInfo =
new ColumnTypeInfo(Types.BOOLEAN, defaultIfNull(extColTypeName, "BOOLEAN"), baseType);
break;
case VECTOR:
columnTypeInfo =
new ColumnTypeInfo(
SnowflakeType.EXTRA_TYPES_VECTOR,
defaultIfNull(extColTypeName, "VECTOR"),
baseType);
break;
case ARRAY:
int columnType = isStructuredType ? Types.ARRAY : Types.VARCHAR;
columnTypeInfo =
new ColumnTypeInfo(columnType, defaultIfNull(extColTypeName, "ARRAY"), baseType);
break;
case MAP:
columnTypeInfo =
new ColumnTypeInfo(Types.STRUCT, defaultIfNull(extColTypeName, "OBJECT"), baseType);
break;
case OBJECT:
if (isStructuredType) {
boolean isGeoType =
"GEOMETRY".equals(extColTypeName) || "GEOGRAPHY".equals(extColTypeName);
int type = isGeoType ? Types.VARCHAR : Types.STRUCT;
columnTypeInfo =
new ColumnTypeInfo(type, defaultIfNull(extColTypeName, "OBJECT"), baseType);
} else {
columnTypeInfo =
new ColumnTypeInfo(Types.VARCHAR, defaultIfNull(extColTypeName, "OBJECT"), baseType);
}
break;
case VARIANT:
columnTypeInfo =
new ColumnTypeInfo(Types.VARCHAR, defaultIfNull(extColTypeName, "VARIANT"), baseType);
break;
case BINARY:
columnTypeInfo =
new ColumnTypeInfo(Types.BINARY, defaultIfNull(extColTypeName, "BINARY"), baseType);
break;
case GEOGRAPHY:
case GEOMETRY:
int colType = Types.VARCHAR;
extColTypeName = (baseType == GEOGRAPHY) ? "GEOGRAPHY" : "GEOMETRY";
if (!udtOutputType.isMissingNode()) {
SnowflakeType outputType = SnowflakeTypeUtil.fromStringOrNull(udtOutputType.asText());
if (outputType != null) {
switch (outputType) {
case OBJECT:
case TEXT:
colType = Types.VARCHAR;
break;
case BINARY:
colType = Types.BINARY;
}
}
}
columnTypeInfo = new ColumnTypeInfo(colType, extColTypeName, baseType);
break;
default:
throw new SnowflakeSQLLoggedException(
session,
ErrorCode.INTERNAL_ERROR.getMessageCode(),
SqlState.INTERNAL_ERROR,
"Unknown column type: " + internalColTypeName);
}
return columnTypeInfo;
}
private static String defaultIfNull(String extColTypeName, String defaultValue) {
return Optional.ofNullable(extColTypeName).orElse(defaultValue);
}
static List<FieldMetadata> createFieldsMetadata(
ArrayNode fieldsJson, boolean jdbcTreatDecimalAsInt, String parentInternalColumnTypeName)
throws SnowflakeSQLLoggedException {
List<FieldMetadata> fields = new ArrayList<>();
for (JsonNode node : fieldsJson) {
String colName;
if (!node.path("fieldType").isEmpty()) {
colName = node.path("fieldName").asText();
node = node.path("fieldType");
} else {
colName = node.path("name").asText();
}
int scale = node.path("scale").asInt();
int precision = node.path("precision").asInt();
String internalColTypeName = node.path("type").asText();
boolean nullable = node.path("nullable").asBoolean();
int length = node.path("length").asInt();
boolean fixed = node.path("fixed").asBoolean();
int fixedColType = jdbcTreatDecimalAsInt && scale == 0 ? Types.BIGINT : Types.DECIMAL;
List<FieldMetadata> internalFields =
getFieldMetadata(jdbcTreatDecimalAsInt, parentInternalColumnTypeName, node);
JsonNode outputType = node.path("outputType");
JsonNode extColTypeNameNode = node.path("extTypeName");
String extColTypeName = null;
if (!extColTypeNameNode.isMissingNode() && !isNullOrEmpty(extColTypeNameNode.asText())) {
extColTypeName = extColTypeNameNode.asText();
}
ColumnTypeInfo columnTypeInfo =
getSnowflakeType(
internalColTypeName,
extColTypeName,
outputType,
null,
fixedColType,
internalFields.size() > 0,
isVectorType(parentInternalColumnTypeName));
fields.add(
new FieldMetadataImpl(
colName,
columnTypeInfo.getExtColTypeName(),
columnTypeInfo.getColumnType(),
nullable,
length,
precision,
scale,
fixed,
columnTypeInfo.getSnowflakeType(),
internalFields));
}
return fields;
}
static boolean isVectorType(String internalColumnTypeName) {
return internalColumnTypeName.equalsIgnoreCase("vector");
}
static List<FieldMetadata> getFieldMetadata(
boolean jdbcTreatDecimalAsInt, String internalColumnTypeName, JsonNode node)
throws SnowflakeSQLLoggedException {
if (!node.path("fields").isEmpty()) {
ArrayNode internalFieldsJson = (ArrayNode) node.path("fields");
return createFieldsMetadata(
internalFieldsJson, jdbcTreatDecimalAsInt, internalColumnTypeName);
} else {
return new ArrayList<>();
}
}
public static String javaTypeToSFTypeString(int javaType, SFBaseSession session)
throws SnowflakeSQLException {
return SnowflakeTypeUtil.javaTypeToSFType(javaType, session).name();
}
public static SnowflakeType javaTypeToSFType(int javaType, SFBaseSession session)
throws SnowflakeSQLException {
return SnowflakeTypeUtil.javaTypeToSFType(javaType, session);
}
/**
* A small function for concatenating two file paths by making sure one and only one path
* separator is placed between the two paths.
*
* <p>This is necessary since for S3 file name, having different number of file separators in a
* path will mean different files.
*
* <p>Typical use case is to concatenate a file name to a directory.
*
* @param leftPath left path
* @param rightPath right path
* @param fileSep file separator
* @return concatenated file path
*/
static String concatFilePathNames(String leftPath, String rightPath, String fileSep) {
String leftPathTrimmed = leftPath.trim();
String rightPathTrimmed = rightPath.trim();
if (leftPathTrimmed.isEmpty()) {
return rightPath;
}
if (leftPathTrimmed.endsWith(fileSep) && rightPathTrimmed.startsWith(fileSep)) {
return leftPathTrimmed + rightPathTrimmed.substring(1);
} else if (!leftPathTrimmed.endsWith(fileSep) && !rightPathTrimmed.startsWith(fileSep)) {
return leftPathTrimmed + fileSep + rightPathTrimmed;
} else {
return leftPathTrimmed + rightPathTrimmed;
}
}
static String greatestCommonPrefix(String val1, String val2) {
if (val1 == null || val2 == null) {
return null;
}
StringBuilder greatestCommonPrefix = new StringBuilder();
int len = Math.min(val1.length(), val2.length());
for (int idx = 0; idx < len; idx++) {
if (val1.charAt(idx) == val2.charAt(idx)) {
greatestCommonPrefix.append(val1.charAt(idx));
} else {
break;
}
}
return greatestCommonPrefix.toString();
}
static List<SnowflakeColumnMetadata> describeFixedViewColumns(
Class<?> clazz, SFBaseSession session) throws SnowflakeSQLException {
Field[] columns = ClassUtil.getAnnotatedDeclaredFields(clazz, FixedViewColumn.class, true);
Arrays.sort(columns, new FixedViewColumn.OrdinalComparatorForFields());
List<SnowflakeColumnMetadata> rowType = new ArrayList<SnowflakeColumnMetadata>();
for (Field column : columns) {
FixedViewColumn columnAnnotation = column.getAnnotation(FixedViewColumn.class);
String typeName;
int colType;
Class<?> type = column.getType();
SnowflakeType stype = SnowflakeType.TEXT;
if (type == Integer.TYPE) {
colType = Types.INTEGER;
typeName = "INTEGER";
stype = SnowflakeType.INTEGER;
}
if (type == Long.TYPE) {
colType = Types.DECIMAL;
typeName = "DECIMAL";
stype = SnowflakeType.INTEGER;
} else if (type == String.class) {
colType = Types.VARCHAR;
typeName = "VARCHAR";
stype = SnowflakeType.TEXT;
} else {
throw new SnowflakeSQLLoggedException(
session,
ErrorCode.INTERNAL_ERROR.getMessageCode(),
SqlState.INTERNAL_ERROR,
"Unsupported column type: " + type.getName());
}
// TODO: we hard code some of the values below but can change them
// later to derive from annotation as well.
rowType.add(
new SnowflakeColumnMetadata(
columnAnnotation.name(), // column name
colType, // column type
false, // nullable
20480, // length
10, // precision
0, // scale
typeName, // type name
true,
stype, // fixed
new ArrayList<>(),
"", // database
"", // schema
"",
false, // isAutoincrement
0 // dimension
));
}
return rowType;
}
/**
* A utility to log response details.
*
* <p>Used when there is an error in http response
*
* @param response http response get from server
* @param logger logger object
*/
public static void logResponseDetails(HttpResponse response, SFLogger logger) {
if (response == null) {
logger.error("null response", false);
return;
}
// log the response
if (response.getStatusLine() != null) {
logger.error("Response status line reason: {}", response.getStatusLine().getReasonPhrase());
}
// log each header from response
Header[] headers = response.getAllHeaders();
if (headers != null) {
for (Header header : headers) {
logger.debug("Header name: {}, value: {}", header.getName(), header.getValue());
}
}
// log response
if (response.getEntity() != null) {
try {
StringWriter writer = new StringWriter();
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
IOUtils.copy(bufferedReader, writer);
logger.error("Response content: {}", writer.toString());
} catch (IOException ex) {
logger.error("Failed to read content due to exception: " + "{}", ex.getMessage());
}
}
}
/**
* Returns a new thread pool configured with the default settings.
*
* @param threadNamePrefix prefix of the thread name
* @param parallel the number of concurrency
* @return A new thread pool configured with the default settings.
*/
public static ThreadPoolExecutor createDefaultExecutorService(
final String threadNamePrefix, final int parallel) {
ThreadFactory threadFactory =
new ThreadFactory() {
private int threadCount = 1;
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName(threadNamePrefix + threadCount++);
return thread;
}
};
return (ThreadPoolExecutor) Executors.newFixedThreadPool(parallel, threadFactory);
}
public static Throwable getRootCause(Exception ex) {
Throwable cause = ex;
while (cause.getCause() != null) {
cause = cause.getCause();
}
return cause;
}
/**
* Walks the exception cause chain and returns the first {@link Throwable} that is an instance of
* {@code type}, or {@code null} if none is found. Unlike {@link #getRootCause(Exception)}, which
* always returns the deepest cause, this method stops at the first match of the requested type.
*/
public static <T extends Throwable> T findFirstCauseOfType(Throwable ex, Class<T> type) {
Throwable cause = ex;
while (cause != null) {
if (type.isInstance(cause)) {
return type.cast(cause);
}
cause = cause.getCause();
}
return null;
}
public static boolean isBlank(String input) {
if ("".equals(input) || input == null) {
return true;
}
for (char c : input.toCharArray()) {
if (!Character.isWhitespace(c)) {
return false;
}
}
return true;
}
private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
public static String randomAlphaNumeric(int count) {
StringBuilder builder = new StringBuilder();
Random random = new Random();
while (count-- != 0) {
int character = random.nextInt(ALPHA_NUMERIC_STRING.length());
builder.append(ALPHA_NUMERIC_STRING.charAt(character));
}
return builder.toString();
}
/**
* System.getProperty wrapper. If System.getProperty raises a SecurityException, it is ignored and
* returns null.
*
* @param property the property name
* @return the property value if set, otherwise null.
*/
public static String systemGetProperty(String property) {
try {
return System.getProperty(property);
} catch (SecurityException ex) {
// logger may be null during SnowflakeUtil.<clinit> (circular init via SFLoggerFactory)
if (logger != null) {
logger.debug("Security exception raised: {}", ex.getMessage());
}
return null;
}
}
/**
* System.setProperty wrapper. If System.setProperty raises a SecurityException, it is ignored.
*
* @param property the property name
* @param value the property value
*/
public static void systemSetProperty(String property, String value) {
try {
System.setProperty(property, value);
} catch (SecurityException ex) {
// logger may be null during SnowflakeUtil.<clinit> (circular init via SFLoggerFactory)
if (logger != null) {
logger.debug("Security exception raised: {}", ex.getMessage());
}
}
}
/**
* System.getenv wrapper. If System.getenv raises a SecurityException, it is ignored and returns
* null.
*
* @param env the environment variable name.
* @return the environment variable value if set, otherwise null.
*/
public static String systemGetEnv(String env) {
try {
return System.getenv(env);
} catch (SecurityException ex) {
// logger may be null during SnowflakeUtil.<clinit> (circular init via SFLoggerFactory)
if (logger != null) {
logger.debug(
"Failed to get environment variable {}. Security exception raised: {}",
env,
ex.getMessage());
}
}
return null;
}
/**
* System.setEnv function. Can be used for unit tests.
*
* @param key key
* @param value value
*/
public static void systemSetEnv(String key, String value) {
try {
Map<String, String> env = System.getenv();
Class<?> cl = env.getClass();
Field field = cl.getDeclaredField("m");
field.setAccessible(true);
Map<String, String> writableEnv = (Map<String, String>) field.get(env);
writableEnv.put(key, value);
// To an environment variable is set on Windows, it uses a different map to store the values
// when the system.getenv(VAR_NAME) is used its required to update in this additional place.
if (Constants.getOS() == Constants.OS.WINDOWS) {
Class<?> pe = Class.forName("java.lang.ProcessEnvironment");
Method getenv = pe.getDeclaredMethod("getenv", String.class);
getenv.setAccessible(true);
Field props = pe.getDeclaredField("theCaseInsensitiveEnvironment");
props.setAccessible(true);
Map<String, String> writableEnvForGet = (Map<String, String>) props.get(null);
writableEnvForGet.put(key, value);
}
} catch (Exception e) {
logger.error(
"Failed to set environment variable {}. Exception raised: {}", key, e.getMessage());
}
}
/**
* System.unsetEnv function to remove a system environment parameter in the map
*
* @param key key value
*/
public static void systemUnsetEnv(String key) {
try {
Map<String, String> env = System.getenv();
Class<?> cl = env.getClass();
Field field = cl.getDeclaredField("m");
field.setAccessible(true);
Map<String, String> writableEnv = (Map<String, String>) field.get(env);
writableEnv.remove(key);
} catch (Exception e) {
logger.error(
"Failed to remove environment variable {}. Exception raised: {}", key, e.getMessage());
}
}
/**
* Setup JDBC proxy properties if necessary.
*
* @param mode OCSP mode
* @param info proxy server properties.
* @return HttpClientSettingsKey
* @throws SnowflakeSQLException if an error occurs
*/
public static HttpClientSettingsKey convertProxyPropertiesToHttpClientKey(
OCSPMode mode, Properties info) throws SnowflakeSQLException {
// Setup proxy properties.
if (info != null
&& info.size() > 0
&& info.getProperty(SFSessionProperty.USE_PROXY.getPropertyKey()) != null) {
Boolean useProxy =
Boolean.valueOf(info.getProperty(SFSessionProperty.USE_PROXY.getPropertyKey()));
if (useProxy) {
// set up other proxy related values.
String proxyHost = info.getProperty(SFSessionProperty.PROXY_HOST.getPropertyKey());
int proxyPort;
try {
proxyPort =
Integer.parseInt(info.getProperty(SFSessionProperty.PROXY_PORT.getPropertyKey()));
} catch (NumberFormatException | NullPointerException e) {
throw new SnowflakeSQLException(
ErrorCode.INVALID_PROXY_PROPERTIES, "Could not parse port number");
}
String proxyUser = info.getProperty(SFSessionProperty.PROXY_USER.getPropertyKey());
String proxyPassword = info.getProperty(SFSessionProperty.PROXY_PASSWORD.getPropertyKey());
String nonProxyHosts = info.getProperty(SFSessionProperty.NON_PROXY_HOSTS.getPropertyKey());
String proxyProtocol = info.getProperty(SFSessionProperty.PROXY_PROTOCOL.getPropertyKey());
String userAgentSuffix =
info.getProperty(SFSessionProperty.USER_AGENT_SUFFIX.getPropertyKey());
Boolean gzipDisabled =
isNullOrEmpty(info.getProperty(SFSessionProperty.GZIP_DISABLED.getPropertyKey()))
? false
: Boolean.valueOf(
info.getProperty(SFSessionProperty.GZIP_DISABLED.getPropertyKey()));
// create key for proxy properties
return new HttpClientSettingsKey(
mode,
proxyHost,
proxyPort,
nonProxyHosts,
proxyUser,
proxyPassword,
proxyProtocol,
userAgentSuffix,
gzipDisabled);
}
}
// if no proxy properties, return key with only OCSP mode
return new HttpClientSettingsKey(mode);
}
/**
* Round the time value from milliseconds to seconds so the seconds can be used to create
* SimpleDateFormatter. Negative values have to be rounded to the next negative value, while
* positive values should be cut off with no rounding.
*
* @param millis milliseconds
* @return seconds as long value
*/
public static long getSecondsFromMillis(long millis) {
long returnVal;
if (millis < 0) {
returnVal = (long) Math.ceil((double) Math.abs(millis) / 1000);
returnVal *= -1;
} else {
returnVal = millis / 1000;
}
return returnVal;
}
/**
* Get the time value in session timezone instead of UTC calculation done by java.sql.Time.
*
* @param time time in seconds
* @param nanos nanoseconds
* @return time in session timezone
*/
public static Time getTimeInSessionTimezone(Long time, int nanos) {
LocalDateTime lcd = LocalDateTime.ofEpochSecond(time, nanos, ZoneOffset.UTC);
Time ts = Time.valueOf(lcd.toLocalTime());
// Time.valueOf() will create the time without the nanoseconds i.e. only hh:mm:ss
// Using calendar to add the nanoseconds back to time
Calendar c = Calendar.getInstance();
c.setTimeInMillis(ts.getTime());
c.add(Calendar.MILLISECOND, nanos / 1000000);
ts.setTime(c.getTimeInMillis());
return ts;
}
/**
* Helper function to convert system properties to boolean
*
* @param systemProperty name of the system property
* @param defaultValue default value used
* @return the value of the system property as boolean, else the default value
*/
public static boolean convertSystemPropertyToBooleanValue(
String systemProperty, boolean defaultValue) {
String systemPropertyValue = systemGetProperty(systemProperty);
if (systemPropertyValue != null) {
return Boolean.parseBoolean(systemPropertyValue);
}
return defaultValue;
}
/**
* Helper function to convert environment variable to boolean
*
* @param envVariableKey property name of the environment variable
* @param defaultValue default value used
* @return the value of the environment variable as boolean, else the default value
*/
public static boolean convertSystemGetEnvToBooleanValue(
String envVariableKey, boolean defaultValue) {
String environmentVariableValue = systemGetEnv(envVariableKey);
if (environmentVariableValue != null) {
return Boolean.parseBoolean(environmentVariableValue);
}
return defaultValue;
}
public static <T> T mapSFExceptionToSQLException(ThrowingCallable<T, SFException> action)
throws SQLException {
try {
return action.call();
} catch (SFException e) {
throw new SQLException(e);
}
}
public static String getJsonNodeStringValue(JsonNode node) throws SFException {
if (node.isNull()) {
return null;
}
return node.isValueNode() ? node.asText() : node.toString();
}
/**
* Method introduced to avoid inconsistencies in custom headers handling, since these are defined
* on drivers side e.g. some drivers might internally convert headers to canonical form.
*
* @param input map input
* @return case insensitive map
*/
public static Map<String, String> createCaseInsensitiveMap(Map<String, String> input) {
Map<String, String> caseInsensitiveMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
if (input != null) {
caseInsensitiveMap.putAll(input);
}
return caseInsensitiveMap;
}
/**
* toCaseInsensitiveMap, but adjusted to Headers[] argument type
*
* @param headers array of headers
* @return case insensitive map
*/
public static Map<String, String> createCaseInsensitiveMap(Header[] headers) {
if (headers != null) {
return createCaseInsensitiveMap(
stream(headers)
.collect(Collectors.toMap(NameValuePair::getName, NameValuePair::getValue)));
} else {
return new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
}
}
/**
* create a directory with Owner only permission (0600)
*
* @param location the directory location
* @return true if directory was created successfully, false otherwise
*/
public static boolean createOwnerOnlyPermissionDir(String location) {
if (isWindows()) {
File dir = new File(location);
return dir.mkdirs();
}
boolean isDirCreated = true;
Path dir = Paths.get(location);
try {
Files.createDirectory(
dir, PosixFilePermissions.asFileAttribute(directoryOwnerOnlyPermission));
} catch (IOException e) {
logger.error(
"Failed to set OwnerOnly permission for {}. This may cause the file download to fail ",
location);
isDirCreated = false;
}
return isDirCreated;
}