/
JdbcTypeConverter.java
449 lines (417 loc) · 18.4 KB
/
JdbcTypeConverter.java
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
/*
* Copyright 2019 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
*
* http://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.
*/
package com.google.cloud.spanner.jdbc;
import com.google.cloud.ByteArray;
import com.google.cloud.Date;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.Type;
import com.google.cloud.spanner.Type.Code;
import com.google.cloud.spanner.Value;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.sql.Array;
import java.sql.SQLException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.threeten.bp.Instant;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZonedDateTime;
import org.threeten.bp.format.DateTimeFormatter;
/** Convenience class for converting values between Java, JDBC and Cloud Spanner. */
class JdbcTypeConverter {
private static final DateTimeFormatter TIMESTAMP_FORMAT = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
private static final Charset UTF8 = Charset.forName("UTF8");
/**
* Converts the given value from the Google {@link Type} to the Java {@link Class} type. The input
* value and the {@link Type} must be consistent with each other.
*
* @param value The value to convert. This value must be in the default type used for a Cloud
* Spanner database type. I.e. if the type argument is {@link Type#string()}, then the input
* value must be an instance of {@link java.lang.String}.
* @param type The type in the database.
* @param targetType The java class target type to convert to.
* @return The converted value.
* @throws SQLException if the given value cannot be converted to the specified type, or if the
* input value and input type are not consistent with each other.
*/
static Object convert(Object value, Type type, Class<?> targetType) throws SQLException {
JdbcPreconditions.checkArgument(type != null, "type may not be null");
JdbcPreconditions.checkArgument(targetType != null, "targetType may not be null");
checkValidTypeAndValueForConvert(type, value);
if (value == null) {
return null;
}
try {
if (targetType.equals(Value.class)) {
return convertToSpannerValue(value, type);
}
if (targetType.equals(String.class)) {
if (type.getCode() == Code.BYTES) return new String((byte[]) value, UTF8);
if (type.getCode() == Code.TIMESTAMP) {
Timestamp timestamp = Timestamp.of((java.sql.Timestamp) value);
return TIMESTAMP_FORMAT.format(
ZonedDateTime.ofInstant(
Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos()),
ZoneId.systemDefault()));
}
return value.toString();
}
if (targetType.equals(byte[].class)) {
if (type.getCode() == Code.BYTES) return value;
if (type.getCode() == Code.STRING) return ((String) value).getBytes(UTF8);
}
if (targetType.equals(Boolean.class)) {
if (type.getCode() == Code.BOOL) return value;
if (type.getCode() == Code.INT64) return Boolean.valueOf((Long) value != 0);
if (type.getCode() == Code.FLOAT64) return Boolean.valueOf((Double) value != 0d);
if (type.getCode() == Code.NUMERIC)
return Boolean.valueOf(!((BigDecimal) value).equals(BigDecimal.ZERO));
}
if (targetType.equals(BigDecimal.class)) {
if (type.getCode() == Code.BOOL) return (Boolean) value ? BigDecimal.ONE : BigDecimal.ZERO;
if (type.getCode() == Code.INT64) return BigDecimal.valueOf((Long) value);
if (type.getCode() == Code.NUMERIC) return value;
}
if (targetType.equals(Long.class)) {
if (type.getCode() == Code.BOOL) return (Boolean) value ? 1L : 0L;
if (type.getCode() == Code.INT64) return value;
if (type.getCode() == Code.NUMERIC)
return AbstractJdbcWrapper.checkedCastToLong((BigDecimal) value);
}
if (targetType.equals(Integer.class)) {
if (type.getCode() == Code.BOOL) return (Boolean) value ? 1 : 0;
if (type.getCode() == Code.INT64) return AbstractJdbcWrapper.checkedCastToInt((Long) value);
if (type.getCode() == Code.NUMERIC)
return AbstractJdbcWrapper.checkedCastToInt((BigDecimal) value);
}
if (targetType.equals(Short.class)) {
if (type.getCode() == Code.BOOL) return (Boolean) value ? 1 : 0;
if (type.getCode() == Code.INT64)
return AbstractJdbcWrapper.checkedCastToShort((Long) value);
if (type.getCode() == Code.NUMERIC)
return AbstractJdbcWrapper.checkedCastToShort((BigDecimal) value);
}
if (targetType.equals(Byte.class)) {
if (type.getCode() == Code.BOOL) return (Boolean) value ? 1 : 0;
if (type.getCode() == Code.INT64)
return AbstractJdbcWrapper.checkedCastToByte((Long) value);
if (type.getCode() == Code.NUMERIC)
return AbstractJdbcWrapper.checkedCastToByte((BigDecimal) value);
}
if (targetType.equals(BigInteger.class)) {
if (type.getCode() == Code.BOOL) return (Boolean) value ? BigInteger.ONE : BigInteger.ZERO;
if (type.getCode() == Code.INT64) return BigInteger.valueOf((Long) value);
if (type.getCode() == Code.NUMERIC)
return AbstractJdbcWrapper.checkedCastToBigInteger((BigDecimal) value);
}
if (targetType.equals(Float.class)) {
if (type.getCode() == Code.BOOL)
return (Boolean) value ? Float.valueOf(1f) : Float.valueOf(0f);
if (type.getCode() == Code.FLOAT64)
return AbstractJdbcWrapper.checkedCastToFloat((Double) value);
if (type.getCode() == Code.NUMERIC) return ((BigDecimal) value).floatValue();
}
if (targetType.equals(Double.class)) {
if (type.getCode() == Code.BOOL)
return (Boolean) value ? Double.valueOf(1d) : Double.valueOf(0d);
if (type.getCode() == Code.FLOAT64) return value;
if (type.getCode() == Code.NUMERIC) return ((BigDecimal) value).doubleValue();
}
if (targetType.equals(java.sql.Date.class)) {
if (type.getCode() == Code.DATE) return value;
}
if (targetType.equals(java.sql.Timestamp.class)) {
if (type.getCode() == Code.TIMESTAMP) return value;
}
if (targetType.equals(java.sql.Array.class)) {
if (type.getCode() == Code.ARRAY) return value;
}
} catch (SQLException e) {
throw e;
} catch (Exception e) {
throw JdbcSqlExceptionFactory.of(
"Cannot convert " + value + " to " + targetType.getName(),
com.google.rpc.Code.INVALID_ARGUMENT,
e);
}
throw JdbcSqlExceptionFactory.of(
"Cannot convert " + type.getCode().name() + " to " + targetType.getName(),
com.google.rpc.Code.INVALID_ARGUMENT);
}
private static Value convertToSpannerValue(Object value, Type type) throws SQLException {
switch (type.getCode()) {
case ARRAY:
switch (type.getArrayElementType().getCode()) {
case BOOL:
return Value.boolArray(Arrays.asList((Boolean[]) ((java.sql.Array) value).getArray()));
case BYTES:
return Value.bytesArray(toGoogleBytes((byte[][]) ((java.sql.Array) value).getArray()));
case DATE:
return Value.dateArray(
toGoogleDates((java.sql.Date[]) ((java.sql.Array) value).getArray()));
case FLOAT64:
return Value.float64Array(
Arrays.asList((Double[]) ((java.sql.Array) value).getArray()));
case INT64:
return Value.int64Array(Arrays.asList((Long[]) ((java.sql.Array) value).getArray()));
case NUMERIC:
return Value.numericArray(
Arrays.asList((BigDecimal[]) ((java.sql.Array) value).getArray()));
case STRING:
return Value.stringArray(Arrays.asList((String[]) ((java.sql.Array) value).getArray()));
case TIMESTAMP:
return Value.timestampArray(
toGoogleTimestamps((java.sql.Timestamp[]) ((java.sql.Array) value).getArray()));
case STRUCT:
default:
throw JdbcSqlExceptionFactory.of(
"invalid argument: " + value, com.google.rpc.Code.INVALID_ARGUMENT);
}
case BOOL:
return Value.bool((Boolean) value);
case BYTES:
return Value.bytes(ByteArray.copyFrom((byte[]) value));
case DATE:
return Value.date(toGoogleDate((java.sql.Date) value));
case FLOAT64:
return Value.float64((Double) value);
case INT64:
return Value.int64((Long) value);
case NUMERIC:
return Value.numeric((BigDecimal) value);
case STRING:
return Value.string((String) value);
case TIMESTAMP:
return Value.timestamp(toGoogleTimestamp((java.sql.Timestamp) value));
case STRUCT:
default:
throw JdbcSqlExceptionFactory.of(
"invalid argument: " + value, com.google.rpc.Code.INVALID_ARGUMENT);
}
}
private static void checkValidTypeAndValueForConvert(Type type, Object value)
throws SQLException {
if (value == null) return;
JdbcPreconditions.checkArgument(
(type.getCode() == Code.ARRAY && Array.class.isAssignableFrom(value.getClass()))
|| type.getCode() != Code.ARRAY,
"input type is array, but input value is not an instance of java.sql.Array");
JdbcPreconditions.checkArgument(
(type.getCode() == Code.BOOL && value.getClass().equals(Boolean.class))
|| type.getCode() != Code.BOOL,
"input type is bool, but input value is not an instance of Boolean");
JdbcPreconditions.checkArgument(
(type.getCode() == Code.BYTES && value.getClass().equals(byte[].class))
|| type.getCode() != Code.BYTES,
"input type is bytes, but input value is not an instance of byte[]");
JdbcPreconditions.checkArgument(
(type.getCode() == Code.DATE && value.getClass().equals(java.sql.Date.class))
|| type.getCode() != Code.DATE,
"input type is date, but input value is not an instance of java.sql.Date");
JdbcPreconditions.checkArgument(
(type.getCode() == Code.FLOAT64 && value.getClass().equals(Double.class))
|| type.getCode() != Code.FLOAT64,
"input type is float64, but input value is not an instance of Double");
JdbcPreconditions.checkArgument(
(type.getCode() == Code.INT64 && value.getClass().equals(Long.class))
|| type.getCode() != Code.INT64,
"input type is int64, but input value is not an instance of Long");
JdbcPreconditions.checkArgument(
(type.getCode() == Code.STRING && value.getClass().equals(String.class))
|| type.getCode() != Code.STRING,
"input type is string, but input value is not an instance of String");
JdbcPreconditions.checkArgument(
(type.getCode() == Code.TIMESTAMP && value.getClass().equals(java.sql.Timestamp.class))
|| type.getCode() != Code.TIMESTAMP,
"input type is timestamp, but input value is not an instance of java.sql.Timestamp");
JdbcPreconditions.checkArgument(
(type.getCode() == Code.NUMERIC && value.getClass().equals(BigDecimal.class))
|| type.getCode() != Code.NUMERIC,
"input type is numeric, but input value is not an instance of BigDecimal");
}
@SuppressWarnings("deprecation")
static Date toGoogleDate(java.sql.Date date) {
return date == null
? null
: Date.fromYearMonthDay(date.getYear() + 1900, date.getMonth() + 1, date.getDate());
}
static Date toGoogleDate(java.sql.Time date) {
return Date.fromYearMonthDay(1970, 1, 1);
}
@SuppressWarnings("deprecation")
static Date toGoogleDate(java.sql.Timestamp date) {
return date == null
? null
: Date.fromYearMonthDay(date.getYear() + 1900, date.getMonth() + 1, date.getDate());
}
static List<Date> toGoogleDates(java.sql.Date[] dates) {
List<com.google.cloud.Date> res = new ArrayList<>(dates.length);
for (int index = 0; index < dates.length; index++) res.add(toGoogleDate(dates[index]));
return res;
}
static java.sql.Date toSqlDate(Date date) {
return toSqlDate(date, Calendar.getInstance());
}
static java.sql.Date toSqlDate(Date date, Calendar cal) {
if (date != null) {
cal.set(date.getYear(), date.getMonth() - 1, date.getDayOfMonth(), 0, 0, 0);
cal.clear(Calendar.MILLISECOND);
return new java.sql.Date(cal.getTimeInMillis());
}
return null;
}
static List<java.sql.Date> toSqlDates(List<Date> dates) {
List<java.sql.Date> res = new ArrayList<>(dates.size());
for (Date date : dates) res.add(toSqlDate(date));
return res;
}
static java.sql.Timestamp toSqlTimestamp(Timestamp ts) {
return ts == null ? null : ts.toSqlTimestamp();
}
static java.sql.Timestamp toSqlTimestamp(Date date) {
return date == null ? null : new java.sql.Timestamp(toSqlDate(date).getTime());
}
static java.sql.Timestamp toSqlTimestamp(Date date, Calendar cal) {
return date == null ? null : new java.sql.Timestamp(toSqlDate(date, cal).getTime());
}
static java.sql.Timestamp getAsSqlTimestamp(Timestamp ts, Calendar cal) {
return ts == null ? null : getTimestampInCalendar(ts.toSqlTimestamp(), cal);
}
static java.sql.Timestamp getTimestampInCalendar(java.sql.Timestamp sqlTs, Calendar cal) {
return getOrSetTimestampInCalendar(sqlTs, cal, GetOrSetTimestampInCalendar.GET);
}
static java.sql.Timestamp setTimestampInCalendar(java.sql.Timestamp sqlTs, Calendar cal) {
return getOrSetTimestampInCalendar(sqlTs, cal, GetOrSetTimestampInCalendar.SET);
}
private enum GetOrSetTimestampInCalendar {
GET,
SET;
}
private static java.sql.Timestamp getOrSetTimestampInCalendar(
java.sql.Timestamp sqlTs, Calendar cal, GetOrSetTimestampInCalendar getOrSet) {
if (sqlTs != null) {
// Get a calendar in the requested timezone
Calendar newCal = Calendar.getInstance(cal.getTimeZone());
// set the millisecond time on this calendar from the timestamp
newCal.setTimeInMillis(sqlTs.getTime());
newCal.set(Calendar.MILLISECOND, 0);
// then shift the time of the calendar by the difference between UTC and the timezone of the
// given calendar
int offset = newCal.getTimeZone().getOffset(newCal.getTimeInMillis());
newCal.add(
Calendar.MILLISECOND, getOrSet == GetOrSetTimestampInCalendar.GET ? offset : -offset);
// then use that to create a sql timestamp
java.sql.Timestamp res = new java.sql.Timestamp(newCal.getTimeInMillis());
// set the nanosecond value that will also set the millisecond value of the timestamp
// as the nanosecond value contains all fraction of a second information
res.setNanos(sqlTs.getNanos());
return res;
}
return null;
}
static List<java.sql.Timestamp> toSqlTimestamps(List<Timestamp> timestamps) {
List<java.sql.Timestamp> res = new ArrayList<>(timestamps.size());
for (Timestamp timestamp : timestamps) {
res.add(toSqlTimestamp(timestamp));
}
return res;
}
static Timestamp toGoogleTimestamp(java.sql.Date ts) {
if (ts != null) {
long milliseconds = ts.getTime();
long seconds = milliseconds / 1000l;
long nanos = (milliseconds - (seconds * 1000)) * 1000000;
return com.google.cloud.Timestamp.ofTimeSecondsAndNanos(seconds, (int) nanos);
}
return null;
}
static Timestamp toGoogleTimestamp(java.sql.Time ts) {
if (ts != null) {
long milliseconds = ts.getTime();
long seconds = milliseconds / 1000l;
long nanos = (milliseconds - (seconds * 1000)) * 1000000;
return com.google.cloud.Timestamp.ofTimeSecondsAndNanos(seconds, (int) nanos);
}
return null;
}
static Timestamp toGoogleTimestamp(java.sql.Timestamp ts) {
if (ts != null) {
long milliseconds = ts.getTime();
long seconds = milliseconds / 1000l;
int nanos = ts.getNanos();
return com.google.cloud.Timestamp.ofTimeSecondsAndNanos(seconds, nanos);
}
return null;
}
static List<Timestamp> toGoogleTimestamps(java.sql.Timestamp[] timestamps) {
List<com.google.cloud.Timestamp> res = new ArrayList<>(timestamps.length);
for (int index = 0; index < timestamps.length; index++) {
res.add(toGoogleTimestamp(timestamps[index]));
}
return res;
}
@SuppressWarnings("deprecation")
static Time toSqlTime(Timestamp ts) {
if (ts != null) {
java.sql.Timestamp sqlTs = toSqlTimestamp(ts);
Time time = new Time(sqlTs.getHours(), sqlTs.getMinutes(), sqlTs.getSeconds());
time.setTime(
time.getTime() + TimeUnit.MILLISECONDS.convert(sqlTs.getNanos(), TimeUnit.NANOSECONDS));
return time;
}
return null;
}
@SuppressWarnings("deprecation")
static Time toSqlTime(Timestamp ts, Calendar cal) {
if (ts != null) {
java.sql.Timestamp sqlTs = getAsSqlTimestamp(ts, cal);
Time time = new Time(sqlTs.getHours(), sqlTs.getMinutes(), sqlTs.getSeconds());
time.setTime(
time.getTime() + TimeUnit.MILLISECONDS.convert(sqlTs.getNanos(), TimeUnit.NANOSECONDS));
return time;
}
return null;
}
@SuppressWarnings("deprecation")
static java.sql.Time parseSqlTime(String val, Calendar cal) {
if (val != null) {
Time time = Time.valueOf(val);
cal.set(1970, 0, 1, time.getHours(), time.getMinutes(), time.getSeconds());
cal.clear(Calendar.MILLISECOND);
return new java.sql.Time(cal.getTimeInMillis());
}
return null;
}
static List<ByteArray> toGoogleBytes(byte[][] bytes) {
List<ByteArray> res = new ArrayList<>(bytes.length);
for (int index = 0; index < bytes.length; index++) {
res.add(bytes[index] == null ? null : ByteArray.copyFrom(bytes[index]));
}
return res;
}
static List<byte[]> toJavaByteArrays(List<ByteArray> bytes) {
List<byte[]> res = new ArrayList<>(bytes.size());
for (ByteArray ba : bytes) {
res.add(ba == null ? null : ba.toByteArray());
}
return res;
}
}