-
Notifications
You must be signed in to change notification settings - Fork 292
/
SpannerSchemaUtils.java
334 lines (297 loc) · 12.4 KB
/
SpannerSchemaUtils.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
/*
* 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.admin;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.OptionalLong;
import java.util.Set;
import java.util.StringJoiner;
import java.util.function.BiFunction;
import com.google.cloud.spanner.Key;
import com.google.cloud.spanner.Type;
import com.google.cloud.spring.data.spanner.core.convert.ConversionUtils;
import com.google.cloud.spring.data.spanner.core.convert.SpannerEntityProcessor;
import com.google.cloud.spring.data.spanner.core.convert.SpannerTypeMapper;
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 org.springframework.data.mapping.PropertyHandler;
import org.springframework.util.Assert;
/**
* Contains functions related to the table schema of entities.
*
* @author Chengyuan Zhao
*
* @since 1.1
*/
public class SpannerSchemaUtils {
private final SpannerMappingContext mappingContext;
private final SpannerEntityProcessor spannerEntityProcessor;
private final boolean createInterleavedTableDdlOnDeleteCascade;
/**
* Constructor. Generates create-table DDL statements that cascade deletes for
* interleaved tables.
* @param mappingContext a mapping context used to obtain persistent entity metadata
* for generating DDL statements.
* @param spannerEntityProcessor an entity processor that is queried for types that it
* can convert for determining compatible column types when generating DDL statements.
* @param createInterleavedTableDdlOnDeleteCascade if {@code true} will generate
* create-table statements that specify cascade on delete for interleaved tables. If
* {@code false}, then the deletes among interleaved tables do not cascade and require
* manual deletion of all children before parents.
*/
public SpannerSchemaUtils(SpannerMappingContext mappingContext,
SpannerEntityProcessor spannerEntityProcessor,
boolean createInterleavedTableDdlOnDeleteCascade) {
Assert.notNull(mappingContext,
"A valid mapping context for Cloud Spanner is required.");
Assert.notNull(spannerEntityProcessor,
"A valid results mapper for Cloud Spanner is required.");
this.mappingContext = mappingContext;
this.spannerEntityProcessor = spannerEntityProcessor;
this.createInterleavedTableDdlOnDeleteCascade = createInterleavedTableDdlOnDeleteCascade;
}
/**
* Gets the DDL string to drop the table for the given entity in Cloud Spanner.
* @param entityClass the entity type.
* @return the DDL string.
*/
public String getDropTableDdlString(Class entityClass) {
return "DROP TABLE "
+ this.mappingContext.getPersistentEntityOrFail(entityClass).tableName();
}
/**
* Gets the key for the given object.
* @param object the object to get the key for
* @return the Spanner Key for the given object.
*/
public Key getKey(Object object) {
SpannerPersistentEntity persistentEntity = this.mappingContext
.getPersistentEntityOrFail(object.getClass());
return (Key) persistentEntity.getPropertyAccessor(object)
.getProperty(persistentEntity.getIdProperty());
}
/**
* Gets the DDL string to create the table for the given entity in Cloud Spanner. This
* is just one of the possible schemas that can support the given entity type. The
* specific schema
* is determined by the configured property type converters used by the read and write
* methods in this SpannerOperations and will be compatible with those methods.
* @param entityClass the entity type.
* @param <T> the type of the entity class
* @return the DDL string.
*/
@SuppressWarnings("unchecked")
public <T> String getCreateTableDdlString(Class<T> entityClass) {
SpannerPersistentEntity<T> spannerPersistentEntity =
(SpannerPersistentEntity<T>) this.mappingContext.getPersistentEntityOrFail(entityClass);
StringBuilder stringBuilder = new StringBuilder()
.append("CREATE TABLE ").append(spannerPersistentEntity.tableName()).append(" ( ");
StringJoiner columnStrings = new StringJoiner(" , ");
addColumnDdlStrings(spannerPersistentEntity, columnStrings);
stringBuilder.append(columnStrings.toString()).append(" ) PRIMARY KEY ( ");
StringJoiner keyStrings = new StringJoiner(" , ");
addPrimaryKeyColumnNames(spannerPersistentEntity, keyStrings);
stringBuilder.append(keyStrings.toString()).append(" )");
return stringBuilder.toString();
}
/**
* Gets a list of DDL strings to create the tables rooted at the given entity class.
* The DDL-create strings are ordered in the list starting with the given root class
* and are topologically sorted.
* @param entityClass the root class for which to get create strings.
* @return a list of create strings that are toplogically sorted from parents to
* children.
*/
public List<String> getCreateTableDdlStringsForInterleavedHierarchy(
Class entityClass) {
List<String> ddlStrings = new ArrayList<>();
getCreateTableDdlStringsForInterleavedHierarchy(null, entityClass, ddlStrings,
new HashSet<>());
return ddlStrings;
}
/**
* Gets the DDL strings to drop the tables of this entity and all of its sub-entities.
* The list is given in reverse topological sort, since parent tables cannot be
* dropped before their children tables.
* @param entityClass the root entity whose table to drop.
* @return the list of drop DDL strings.
*/
public List<String> getDropTableDdlStringsForInterleavedHierarchy(Class entityClass) {
List<String> ddlStrings = new ArrayList<>();
getDropTableDdlStringsForInterleavedHierarchy(entityClass, ddlStrings,
new HashSet<>());
return ddlStrings;
}
String getColumnDdlString(SpannerPersistentProperty spannerPersistentProperty,
SpannerEntityProcessor spannerEntityProcessor) {
Class columnType = spannerPersistentProperty.getType();
String columnName = spannerPersistentProperty.getColumnName() + " ";
Class spannerJavaType;
Type.Code spannerColumnType = spannerPersistentProperty
.getAnnotatedColumnItemType();
if (ConversionUtils.isIterableNonByteArrayType(columnType)) {
Class innerType = spannerPersistentProperty.getColumnInnerType();
spannerJavaType = spannerEntityProcessor
.getCorrespondingSpannerJavaType(innerType, true);
if (spannerColumnType == null) {
spannerColumnType = SpannerTypeMapper.getSimpleTypeCodeForJavaType(spannerJavaType);
}
if (spannerColumnType == null) {
throw new SpannerDataException(
"Could not find suitable Cloud Spanner column inner type for "
+ "property type: " + innerType);
}
return columnName + getTypeDdlString(spannerColumnType, true,
spannerPersistentProperty.getMaxColumnLength(),
spannerPersistentProperty.isGenerateSchemaNotNull(),
spannerPersistentProperty.isCommitTimestamp());
}
if (spannerColumnType == Type.Code.JSON) {
spannerJavaType = columnType;
}
else {
spannerJavaType = spannerEntityProcessor
.getCorrespondingSpannerJavaType(columnType, false);
}
if (spannerJavaType == null) {
throw new SpannerDataException(
"The currently configured custom type converters cannot "
+ "convert the given type to a Cloud Spanner-compatible column type: "
+ columnType);
}
if (spannerColumnType == null) {
spannerColumnType = spannerJavaType.isArray()
? SpannerTypeMapper.getArrayTypeCodeForJavaType(spannerJavaType)
: SpannerTypeMapper.getSimpleTypeCodeForJavaType(spannerJavaType);
}
if (spannerColumnType == null) {
throw new SpannerDataException(
"Could not find suitable Cloud Spanner column type for property "
+ "type :" + columnType);
}
return columnName + getTypeDdlString(spannerColumnType, spannerJavaType.isArray(),
spannerPersistentProperty.getMaxColumnLength(),
spannerPersistentProperty.isGenerateSchemaNotNull(),
spannerPersistentProperty.isCommitTimestamp());
}
private <T> void addPrimaryKeyColumnNames(
SpannerPersistentEntity<T> spannerPersistentEntity, StringJoiner keyStrings) {
for (SpannerPersistentProperty keyProp : spannerPersistentEntity
.getPrimaryKeyProperties()) {
if (keyProp.isEmbedded()) {
addPrimaryKeyColumnNames(
this.mappingContext.getPersistentEntityOrFail(keyProp.getType()),
keyStrings);
}
else {
keyStrings.add(keyProp.getColumnName());
}
}
}
private <T> void addColumnDdlStrings(
SpannerPersistentEntity<T> spannerPersistentEntity,
StringJoiner stringJoiner) {
spannerPersistentEntity.doWithColumnBackedProperties(
spannerPersistentProperty -> {
if (spannerPersistentProperty.isEmbedded()) {
addColumnDdlStrings(
this.mappingContext.getPersistentEntityOrFail(spannerPersistentProperty.getType()),
stringJoiner);
}
else {
stringJoiner.add(getColumnDdlString(spannerPersistentProperty,
this.spannerEntityProcessor));
}
});
}
private void getCreateTableDdlStringsForInterleavedHierarchy(String parentTable,
Class entityClass, List<String> ddlStrings, Set<Class> seenClasses) {
getDdlStringForInterleavedHierarchy(parentTable,
entityClass,
ddlStrings,
seenClasses,
this::generateSingleStringDdl,
false);
}
private String generateSingleStringDdl(Class<?> type, String parent) {
StringBuilder ddlStr = new StringBuilder(getCreateTableDdlString(type));
if (parent != null) {
ddlStr.append(", INTERLEAVE IN PARENT ")
.append(parent)
.append(" ON DELETE ")
.append(this.createInterleavedTableDdlOnDeleteCascade ? "CASCADE" : "NO ACTION");
}
return ddlStr.toString();
}
private void getDropTableDdlStringsForInterleavedHierarchy(Class entityClass,
List<String> dropStrings, Set<Class> seenClasses) {
getDdlStringForInterleavedHierarchy(null, entityClass, dropStrings, seenClasses,
(type, unused) -> getDropTableDdlString(type), true);
}
private void getDdlStringForInterleavedHierarchy(String parentTable,
Class entityClass, List<String> ddlStrings, Set<Class> seenClasses,
BiFunction<Class, String, String> generateSingleDdlStringFunc,
boolean prependDdlString) {
if (seenClasses.contains(entityClass)) {
return;
}
seenClasses.add(entityClass);
ddlStrings.add(prependDdlString ? 0 : ddlStrings.size(),
generateSingleDdlStringFunc.apply(entityClass, parentTable));
SpannerPersistentEntity spannerPersistentEntity =
this.mappingContext.getPersistentEntityOrFail(entityClass);
spannerPersistentEntity.doWithInterleavedProperties(
(PropertyHandler<SpannerPersistentProperty>) spannerPersistentProperty ->
getDdlStringForInterleavedHierarchy(
spannerPersistentEntity.tableName(),
spannerPersistentProperty.getColumnInnerType(), ddlStrings,
seenClasses, generateSingleDdlStringFunc, prependDdlString));
}
private String getTypeDdlString(Type.Code type, boolean isArray,
OptionalLong dataLength, boolean isNotNull, boolean isCommitTimestamp) {
StringBuilder ddlStr = new StringBuilder();
if (isCommitTimestamp) {
ddlStr.append(Type.Code.TIMESTAMP.toString());
}
else {
ddlStr.append(getTypeDdlStringWithLength(type, isArray, dataLength));
}
if (isNotNull) {
ddlStr.append(" NOT NULL");
}
if (isCommitTimestamp) {
ddlStr.append(" OPTIONS (allow_commit_timestamp=true)");
}
return ddlStr.toString();
}
private String getTypeDdlStringWithLength(Type.Code type, boolean isArray,
OptionalLong dataLength) {
Assert.notNull(type, "A valid Spanner column type is required.");
if (isArray) {
return "ARRAY<" + getTypeDdlStringWithLength(type, false, dataLength) + ">";
}
StringBuilder result = new StringBuilder(type.toString());
if (type == Type.Code.STRING || type == Type.Code.BYTES) {
result.append("(")
.append(dataLength.isPresent() ? dataLength.getAsLong() : "MAX")
.append(")");
}
return result.toString();
}
}