/
BaseJdbcAutoSchemaSink.java
283 lines (264 loc) · 11.1 KB
/
BaseJdbcAutoSchemaSink.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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.pulsar.io.jdbc;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.annotations.VisibleForTesting;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import lombok.extern.slf4j.Slf4j;
import org.apache.avro.Schema;
import org.apache.pulsar.client.api.schema.GenericObject;
import org.apache.pulsar.client.api.schema.GenericRecord;
import org.apache.pulsar.client.api.schema.KeyValueSchema;
import org.apache.pulsar.common.schema.KeyValue;
import org.apache.pulsar.functions.api.Record;
import org.apache.pulsar.io.jdbc.JdbcUtils.ColumnId;
/**
* An abstract Jdbc sink, which interprets input Record in generic record.
*/
@Slf4j
public abstract class BaseJdbcAutoSchemaSink extends JdbcAbstractSink<GenericObject> {
@Override
public String generateUpsertQueryStatement() {
throw new IllegalStateException("UPSERT not supported");
}
@Override
public List<ColumnId> getColumnsForUpsert() {
throw new IllegalStateException("UPSERT not supported");
}
@Override
public void bindValue(PreparedStatement statement, Mutation mutation) throws Exception {
final List<ColumnId> columns = new ArrayList<>();
switch (mutation.getType()) {
case INSERT:
columns.addAll(tableDefinition.getColumns());
break;
case UPSERT:
columns.addAll(getColumnsForUpsert());
break;
case UPDATE:
columns.addAll(tableDefinition.getNonKeyColumns());
columns.addAll(tableDefinition.getKeyColumns());
break;
case DELETE:
columns.addAll(tableDefinition.getKeyColumns());
break;
}
int index = 1;
for (ColumnId columnId : columns) {
String colName = columnId.getName();
int colType = columnId.getType();
if (log.isDebugEnabled()) {
log.debug("getting value for column: {} type: {}", colName, colType);
}
try {
Object obj = mutation.getValues().apply(colName);
if (obj != null) {
setColumnValue(statement, index++, obj);
} else {
if (log.isDebugEnabled()) {
log.debug("Column {} is null", colName);
}
setColumnNull(statement, index++, colType);
}
} catch (NullPointerException e) {
// With JSON schema field is omitted, so get NPE
// In this case we want to set column to Null
if (log.isDebugEnabled()) {
log.debug("Column {} is null", colName);
}
setColumnNull(statement, index++, colType);
}
}
}
@Override
public Mutation createMutation(Record<GenericObject> message) {
final GenericObject record = message.getValue();
Function<String, Object> recordValueGetter;
MutationType mutationType = null;
if (message.getSchema() != null && message.getSchema() instanceof KeyValueSchema) {
KeyValueSchema<GenericObject, GenericObject> keyValueSchema = (KeyValueSchema) message.getSchema();
final org.apache.pulsar.client.api.Schema<GenericObject> keySchema = keyValueSchema.getKeySchema();
final org.apache.pulsar.client.api.Schema<GenericObject> valueSchema = keyValueSchema.getValueSchema();
KeyValue<GenericObject, GenericObject> keyValue =
(KeyValue<GenericObject, GenericObject>) record.getNativeObject();
final GenericObject key = keyValue.getKey();
final GenericObject value = keyValue.getValue();
boolean isDelete = false;
if (value == null) {
switch (jdbcSinkConfig.getNullValueAction()) {
case DELETE:
isDelete = true;
break;
case FAIL:
throw new IllegalArgumentException("Got record with value NULL with nullValueAction=FAIL");
default:
break;
}
}
Map<String, Object> data = new HashMap<>();
fillKeyValueSchemaData(keySchema, key, data);
if (isDelete) {
mutationType = MutationType.DELETE;
} else {
fillKeyValueSchemaData(valueSchema, value, data);
}
recordValueGetter = (k) -> data.get(k);
} else {
recordValueGetter = (key) -> ((GenericRecord) record).getField(key);
}
String action = message.getProperties().get(ACTION_PROPERTY);
if (action != null) {
mutationType = MutationType.valueOf(action);
} else if (mutationType == null) {
switch (jdbcSinkConfig.getInsertMode()) {
case INSERT:
mutationType = MutationType.INSERT;
break;
case UPSERT:
mutationType = MutationType.UPSERT;
break;
case UPDATE:
mutationType = MutationType.UPDATE;
break;
default:
throw new IllegalArgumentException("Unknown insert mode: " + jdbcSinkConfig.getInsertMode());
}
}
return new Mutation(mutationType, recordValueGetter);
}
private static void setColumnNull(PreparedStatement statement, int index, int type) throws Exception {
if (log.isDebugEnabled()) {
log.debug("Setting column value to null, statement: {}, index: {}", statement.toString(), index);
}
statement.setNull(index, type);
}
private static void setColumnValue(PreparedStatement statement, int index, Object value) throws Exception {
log.debug("Setting column value, statement: {}, index: {}, value: {}", statement, index, value);
if (value instanceof Integer) {
statement.setInt(index, (Integer) value);
} else if (value instanceof Long) {
statement.setLong(index, (Long) value);
} else if (value instanceof Double) {
statement.setDouble(index, (Double) value);
} else if (value instanceof Float) {
statement.setFloat(index, (Float) value);
} else if (value instanceof Boolean) {
statement.setBoolean(index, (Boolean) value);
} else if (value instanceof String) {
statement.setString(index, (String) value);
} else if (value instanceof Short) {
statement.setShort(index, (Short) value);
} else {
throw new Exception("Not support value type, need to add it. " + value.getClass());
}
}
private static Object getValueFromJsonNode(final JsonNode fn) {
if (fn == null || fn.isNull()) {
return null;
}
if (fn.isContainerNode()) {
throw new IllegalArgumentException("Container nodes are not supported, the JSON must contains only "
+ "first level fields.");
} else if (fn.isBoolean()) {
return fn.asBoolean();
} else if (fn.isFloatingPointNumber()) {
return fn.asDouble();
} else if (fn.isBigInteger()) {
if (fn.canConvertToLong()) {
return fn.asLong();
} else {
return fn.asText();
}
} else if (fn.isNumber()) {
return fn.numberValue();
} else {
return fn.asText();
}
}
private static void fillKeyValueSchemaData(org.apache.pulsar.client.api.Schema<GenericObject> schema,
GenericObject record,
Map<String, Object> data) {
if (record == null) {
return;
}
switch (schema.getSchemaInfo().getType()) {
case JSON:
final JsonNode jsonNode = (JsonNode) record.getNativeObject();
final Iterator<String> fieldNames = jsonNode.fieldNames();
while (fieldNames.hasNext()) {
String fieldName = fieldNames.next();
final JsonNode nodeValue = jsonNode.get(fieldName);
data.put(fieldName, getValueFromJsonNode(nodeValue));
}
break;
case AVRO:
org.apache.avro.generic.GenericRecord avroNode =
(org.apache.avro.generic.GenericRecord) record.getNativeObject();
for (Schema.Field field : avroNode.getSchema().getFields()) {
final String fieldName = field.name();
data.put(fieldName, convertAvroField(avroNode.get(fieldName), field.schema()));
}
break;
default:
throw new IllegalArgumentException("unexpected schema type: "
+ schema.getSchemaInfo().getType()
+ " with KeyValueSchema");
}
}
@VisibleForTesting
static Object convertAvroField(Object avroValue, Schema schema) {
if (avroValue == null) {
return null;
}
switch (schema.getType()) {
case NULL:
case INT:
case LONG:
case DOUBLE:
case FLOAT:
case BOOLEAN:
return avroValue;
case ENUM:
case STRING:
return avroValue.toString(); // can be a String or org.apache.avro.util.Utf8
case UNION:
for (Schema s : schema.getTypes()) {
if (s.getType() == Schema.Type.NULL) {
continue;
}
return convertAvroField(avroValue, s);
}
throw new IllegalArgumentException("Found UNION schema but it doesn't contain any type");
case ARRAY:
case BYTES:
case FIXED:
case RECORD:
case MAP:
default:
throw new UnsupportedOperationException("Unsupported avro schema type=" + schema.getType()
+ " for value field schema " + schema.getName());
}
}
}