-
Notifications
You must be signed in to change notification settings - Fork 292
/
ConverterAwareMappingSpannerEntityWriter.java
431 lines (383 loc) · 15.6 KB
/
ConverterAwareMappingSpannerEntityWriter.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
/*
* Copyright 2017-2019 the original author or authors.
*
* 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.
*/
package com.google.cloud.spring.data.spanner.core.convert;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Predicate;
import com.google.cloud.ByteArray;
import com.google.cloud.Date;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.Key;
import com.google.cloud.spanner.Mutation.WriteBuilder;
import com.google.cloud.spanner.Struct;
import com.google.cloud.spanner.Type;
import com.google.cloud.spanner.Value;
import com.google.cloud.spanner.ValueBinder;
import com.google.cloud.spring.data.spanner.core.mapping.SpannerDataException;
import com.google.cloud.spring.data.spanner.core.mapping.SpannerMappingContext;
import com.google.cloud.spring.data.spanner.core.mapping.SpannerPersistentEntity;
import com.google.cloud.spring.data.spanner.core.mapping.SpannerPersistentProperty;
import com.google.gson.Gson;
import org.springframework.data.mapping.PersistentPropertyAccessor;
import org.springframework.util.Assert;
/**
* The primary class for adding values from entity objects to {@link WriteBuilder} for the
* purpose of creating mutations for Spanner.
*
* @author Chengyuan Zhao
* @author Balint Pato
*
* @since 1.1
*/
public class ConverterAwareMappingSpannerEntityWriter implements SpannerEntityWriter {
private static final Set<Class> SPANNER_KEY_COMPATIBLE_TYPES = Collections.unmodifiableSet(
new HashSet<Class>(
Arrays.asList(
Boolean.class, Integer.class, Long.class, Float.class, Double.class, String.class,
ByteArray.class, Timestamp.class, com.google.cloud.Date.class, BigDecimal.class)));
/**
* A map of types to functions that binds them to `ValueBinder` objects.
*/
public static final Map<Class<?>, BiFunction<ValueBinder, ?, ?>> singleItemTypeValueBinderMethodMap;
static final Map<Class<?>, BiConsumer<ValueBinder<?>, Iterable>>
iterablePropertyTypeToMethodMap = createIterableTypeMapping();
private static final Gson gson = new Gson();
@SuppressWarnings("unchecked")
private static Map<Class<?>, BiConsumer<ValueBinder<?>, Iterable>> createIterableTypeMapping() {
Map<Class<?>, BiConsumer<ValueBinder<?>, Iterable>> map = new LinkedHashMap<>();
map.put(Boolean.class, ValueBinder::toBoolArray);
map.put(Long.class, ValueBinder::toInt64Array);
map.put(Double.class, ValueBinder::toFloat64Array);
map.put(BigDecimal.class, ValueBinder::toNumericArray);
map.put(Timestamp.class, ValueBinder::toTimestampArray);
map.put(Date.class, ValueBinder::toDateArray);
map.put(ByteArray.class, ValueBinder::toBytesArray);
map.put(String.class, ValueBinder::toStringArray);
return Collections.unmodifiableMap(map);
}
static {
Map<Class<?>, BiFunction<ValueBinder, ?, ?>> map = new LinkedHashMap<>();
map.put(Boolean.class, (BiFunction<ValueBinder, Boolean, ?>) ValueBinder::to);
map.put(Long.class, (BiFunction<ValueBinder, Long, ?>) ValueBinder::to);
map.put(long.class, (BiFunction<ValueBinder, Long, ?>) ValueBinder::to);
map.put(Double.class, (BiFunction<ValueBinder, Double, ?>) ValueBinder::to);
map.put(double.class, (BiFunction<ValueBinder, Double, ?>) ValueBinder::to);
map.put(BigDecimal.class, (BiFunction<ValueBinder, BigDecimal, ?>) ValueBinder::to);
map.put(Timestamp.class,
(BiFunction<ValueBinder, Timestamp, ?>) ValueBinder::to);
map.put(Date.class, (BiFunction<ValueBinder, Date, ?>) ValueBinder::to);
map.put(ByteArray.class,
(BiFunction<ValueBinder, ByteArray, ?>) ValueBinder::to);
map.put(String.class, (BiFunction<ValueBinder, String, ?>) ValueBinder::to);
map.put(double[].class,
(BiFunction<ValueBinder, double[], ?>) ValueBinder::toFloat64Array);
map.put(boolean[].class,
(BiFunction<ValueBinder, boolean[], ?>) ValueBinder::toBoolArray);
map.put(long[].class,
(BiFunction<ValueBinder, long[], ?>) ValueBinder::toInt64Array);
map.put(Struct.class, (BiFunction<ValueBinder, Struct, ?>) ValueBinder::to);
singleItemTypeValueBinderMethodMap = Collections.unmodifiableMap(map);
}
private final SpannerMappingContext spannerMappingContext;
private final SpannerWriteConverter writeConverter;
ConverterAwareMappingSpannerEntityWriter(SpannerMappingContext spannerMappingContext,
SpannerWriteConverter writeConverter) {
this.spannerMappingContext = spannerMappingContext;
this.writeConverter = writeConverter;
}
public static Class<?> findFirstCompatibleSpannerSingleItemNativeType(Predicate<Class> testFunc) {
return singleItemTypeValueBinderMethodMap.keySet().stream().filter(testFunc)
.findFirst().orElse(null);
}
public static Class<?> findFirstCompatibleSpannerMultipleItemNativeType(Predicate<Class> testFunc) {
return iterablePropertyTypeToMethodMap.keySet().stream().filter(testFunc).findFirst().orElse(null);
}
@Override
public void write(Object source, MultipleValueBinder sink) {
write(source, sink, null);
}
/**
* Writes an object's properties to the sink.
* @param source the object to write
* @param sink the sink to which to write
* @param includeColumns the columns to write. If null, then all columns are written.
*/
public void write(Object source, MultipleValueBinder sink,
Set<String> includeColumns) {
boolean writeAllColumns = includeColumns == null;
SpannerPersistentEntity<?> persistentEntity = this.spannerMappingContext
.getPersistentEntityOrFail(source.getClass());
PersistentPropertyAccessor accessor = persistentEntity
.getPropertyAccessor(source);
persistentEntity.doWithColumnBackedProperties(
spannerPersistentProperty -> {
if (spannerPersistentProperty.isEmbedded()) {
Object embeddedObject = accessor
.getProperty(spannerPersistentProperty);
if (embeddedObject != null) {
write(embeddedObject, sink, includeColumns);
}
}
else if (writeAllColumns || includeColumns
.contains(spannerPersistentProperty.getColumnName())) {
writeProperty(sink, accessor, spannerPersistentProperty);
}
});
}
@Override
public Key convertToKey(Object key) {
Assert.notNull(key, "Key of an entity to be written cannot be null!");
Key k;
boolean isIterable = Iterable.class.isAssignableFrom(key.getClass());
boolean isArray = Object[].class.isAssignableFrom(key.getClass());
if ((isIterable || isArray) && !ByteArray.class.isAssignableFrom(key.getClass())) {
Key.Builder kb = Key.newBuilder();
for (Object keyPart : (isArray ? (Arrays.asList((Object[]) key))
: ((Iterable) key))) {
kb.appendObject(convertKeyPart(keyPart));
}
k = kb.build();
if (k.size() == 0) {
throw new SpannerDataException(
"A key must have at least one component, but 0 were given.");
}
}
else {
k = Key.class.isAssignableFrom(key.getClass()) ? (Key) key
: Key.of(convertKeyPart(key));
}
return k;
}
@Override
public SpannerWriteConverter getSpannerWriteConverter() {
return this.writeConverter;
}
/**
* Bind an iterable value to a ValueBinder.
*
* @param value the value to bind.
* @param valueBinder the binder that accepts the value.
* @param writeConverter the converter to use to convert the values.
* @param innerType the type of the items in the iterable.
* @return {@code true} if the binding was successful.
*/
public static boolean attemptSetIterableValueOnBinder(Iterable<Object> value, ValueBinder valueBinder,
SpannerCustomConverter writeConverter, Class innerType) {
boolean valueSet = false;
// attempt check if there is directly a write method that can accept the
// property
if (iterablePropertyTypeToMethodMap.containsKey(innerType)) {
iterablePropertyTypeToMethodMap.get(innerType).accept(valueBinder,
value);
valueSet = true;
}
// Finally find any compatible conversion
if (!valueSet) {
for (Class<?> targetType : iterablePropertyTypeToMethodMap.keySet()) {
valueSet = attemptSetIterablePropertyWithTypeConversion(value, valueBinder,
innerType, targetType, writeConverter);
if (valueSet) {
break;
}
}
}
return valueSet;
}
/**
* Bind a value to a ValueBinder.
*
* @param propertyValue the value to bind.
* @param propertyType the type of the value to bind.
* @param valueBinder the binder.
* @param spannerCustomConverter the converter used to convert if necessary.
* @return {@code true} if the value was bound successfully.
*/
public static boolean attemptBindSingleValue(Object propertyValue, Class<?> propertyType, ValueBinder valueBinder,
SpannerCustomConverter spannerCustomConverter) {
// directly try to set using the property's original Java type
boolean valueSet = attemptSetSingleItemValue(propertyValue, propertyType,
valueBinder, propertyType, spannerCustomConverter);
// Finally try and find any conversion that works
if (!valueSet) {
for (Class<?> targetType : singleItemTypeValueBinderMethodMap.keySet()) {
valueSet = attemptSetSingleItemValue(propertyValue, propertyType,
valueBinder, targetType, spannerCustomConverter);
if (valueSet) {
break;
}
}
}
return valueSet;
}
private static boolean attemptSetIterablePropertyWithTypeConversion(Iterable<Object> value,
ValueBinder<WriteBuilder> valueBinder, Class innerType, Class<?> targetType,
SpannerCustomConverter writeConverter) {
if (writeConverter.canConvert(innerType, targetType)) {
BiConsumer<ValueBinder<?>, Iterable> toMethod = iterablePropertyTypeToMethodMap
.get(targetType);
toMethod.accept(valueBinder,
(value != null) ? ConversionUtils.convertIterable(value, targetType, writeConverter) : null);
return true;
}
return false;
}
private Object convertKeyPart(Object object) {
if (object == null || isValidSpannerKeyType(ConversionUtils.boxIfNeeded(object.getClass()))) {
return object;
}
/*
* Iterate through the supported Key component types in the same order as the write
* converter. For example, if a type can be converted to both String and Double, we want
* both the this key conversion and the write converter to choose the same.
*/
Class<?> compatible = ConverterAwareMappingSpannerEntityWriter
.findFirstCompatibleSpannerSingleItemNativeType(spannerType -> isValidSpannerKeyType(spannerType)
&& this.writeConverter.canConvert(object.getClass(), spannerType));
if (compatible == null) {
throw new SpannerDataException(
"The given object type couldn't be built into a Cloud Spanner Key: "
+ object.getClass());
}
return this.writeConverter.convert(object, compatible);
}
private boolean isValidSpannerKeyType(Class type) {
return SPANNER_KEY_COMPATIBLE_TYPES.contains(type);
}
// @formatter:off
private static boolean attemptSetIterableValue(Iterable<Object> value,
ValueBinder<WriteBuilder> valueBinder,
SpannerPersistentProperty spannerPersistentProperty, SpannerCustomConverter writeConverter) {
Class innerType = ConversionUtils.boxIfNeeded(spannerPersistentProperty.getColumnInnerType());
if (innerType == null) {
return false;
}
boolean valueSet = false;
// use the annotated column type if possible.
if (spannerPersistentProperty.getAnnotatedColumnItemType() != null) {
valueSet = attemptSetIterablePropertyWithTypeConversion(value, valueBinder, innerType,
SpannerTypeMapper.getSimpleJavaClassFor(
spannerPersistentProperty.getAnnotatedColumnItemType()),
writeConverter);
}
else {
valueSet = attemptSetIterableValueOnBinder(value, valueBinder, writeConverter, innerType);
}
return valueSet;
}
@SuppressWarnings("unchecked")
private static <T> boolean attemptSetSingleItemValue(Object value, Class<?> sourceType,
ValueBinder<WriteBuilder> valueBinder, Class<T> targetType, SpannerCustomConverter writeConverter) {
if (!writeConverter.canConvert(sourceType, targetType)) {
return false;
}
Class innerType = ConversionUtils.boxIfNeeded(targetType);
BiFunction<ValueBinder, T, ?> toMethod = (BiFunction<ValueBinder, T, ?>) singleItemTypeValueBinderMethodMap
.get(innerType);
if (toMethod == null) {
return false;
}
// We're just checking for the bind to have succeeded, we don't need to chain the result.
// Spanner allows binding of null values.
Object ignored = toMethod.apply(valueBinder,
(value != null) ? writeConverter.convert(value, targetType) : null);
return true;
}
private static Value covertJsonToValue(Object value) {
if (value == null) {
return Value.json(null);
}
String jsonString = gson.toJson(value);
return Value.json(jsonString);
}
/**
* <p>
* For each property this method "set"s the column name and finds the corresponding "to"
* method on the {@link ValueBinder} interface.
* </p>
* <pre>
* {
* @code
*
* long singerId = my_singer_id;
* Mutation.WriteBuilder writeBuilder = Mutation.newInsertBuilder("Singer")
* .set("SingerId")
* .to(singerId)
* .set("FirstName")
* .to("Billy")
* .set("LastName")
* .to("Joel");
* }
* </pre>
*
* @param accessor the accessor used to get the value to write
* @param property the property that will be written
* @param sink the object that will accept the value to be written
*/
// @formatter:on
@SuppressWarnings("unchecked")
private void writeProperty(MultipleValueBinder sink,
PersistentPropertyAccessor accessor,
SpannerPersistentProperty property) {
Object propertyValue = accessor.getProperty(property);
Class<?> propertyType = property.getType();
ValueBinder<WriteBuilder> valueBinder = sink.set(property.getColumnName());
boolean valueSet = false;
/*
* Due to type erasure, binder methods for Iterable properties must be manually specified.
* ByteArray must be excluded since it implements Iterable, but is also explicitly
* supported by spanner.
*/
if (ConversionUtils.isIterableNonByteArrayType(propertyType)) {
valueSet = attemptSetIterableValue((Iterable<Object>) propertyValue, valueBinder,
property, this.writeConverter);
}
else {
// if the property is a commit timestamp, then its Spanner column type is always TIMESTAMP
// and only the dummy value needs to be written to trigger auto-population of the commit
// time
if (property.isCommitTimestamp()) {
valueSet = attemptSetSingleItemValue(Value.COMMIT_TIMESTAMP, Timestamp.class, valueBinder,
Timestamp.class, this.writeConverter);
}
// annotated json column, bind directly
else if (property.getAnnotatedColumnItemType() == Type.Code.JSON) {
valueBinder.to(covertJsonToValue(propertyValue));
valueSet = true;
}
// use the user's annotated column type if possible
else if (property.getAnnotatedColumnItemType() != null) {
valueSet = attemptSetSingleItemValue(propertyValue, propertyType,
valueBinder,
SpannerTypeMapper.getSimpleJavaClassFor(property.getAnnotatedColumnItemType()),
this.writeConverter);
}
else {
valueSet = attemptBindSingleValue(propertyValue, propertyType, valueBinder, this.writeConverter);
}
}
if (!valueSet) {
throw new SpannerDataException(String.format(
"Unsupported mapping for type: %s", propertyType));
}
}
}