1 package org.wikimedia.eventutilities.flink.table;
2
3 import java.util.List;
4 import java.util.Map;
5 import java.util.stream.Collectors;
6
7 import javax.annotation.Nonnull;
8 import javax.annotation.Nullable;
9
10 import org.apache.commons.compress.utils.Lists;
11 import org.apache.flink.table.api.Schema;
12 import org.apache.flink.table.catalog.CatalogBaseTable;
13 import org.apache.flink.table.catalog.CatalogTable;
14 import org.apache.flink.table.catalog.exceptions.CatalogException;
15 import org.wikimedia.eventutilities.core.event.EventStream;
16
17 import com.google.common.collect.LinkedHashMultiset;
18
19 public final class EventTableUtils {
20
21
22
23
24
25
26
27
28
29
30
31
32 public static CatalogBaseTable getTableOfEventStream(
33 EventStream eventStream,
34 String schemaVersion,
35 Map<String, String> tableOptions,
36 @Nullable String comment,
37 @Nullable List<Schema.UnresolvedColumn> otherColumns
38 ) throws CatalogException {
39 return getTableOfEventStream(eventStream, schemaVersion, tableOptions, comment, otherColumns, null, null);
40 }
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55 public static CatalogBaseTable getTableOfEventStream(
56 EventStream eventStream,
57 String schemaVersion,
58 @Nonnull Map<String, String> tableOptions,
59 @Nullable String comment,
60 @Nullable List<Schema.UnresolvedColumn> otherColumns,
61 @Nullable String watermarkColumn,
62 @Nullable Integer watermarkDelay
63 ) throws CatalogException {
64 Schema.Builder schemaBuilder = SchemaBuilderUtil.createEventStreamSchemaBuilder(eventStream, schemaVersion);
65 if (otherColumns != null) {
66 schemaBuilder.fromColumns(otherColumns);
67 }
68 if (watermarkColumn != null && watermarkDelay != null) {
69 schemaBuilder = SchemaBuilderUtil.withKafkaTimestampAsWatermark(schemaBuilder, watermarkColumn, watermarkDelay);
70 }
71 Schema schema = schemaBuilder.build();
72
73 List<String> columns = schema.getColumns()
74 .stream().map(Schema.UnresolvedColumn::getName).collect(Collectors.toList());
75 if (columns.size() != columns.stream().distinct().count()) {
76 LinkedHashMultiset<String> duplicates = LinkedHashMultiset.create(columns);
77 duplicates.entrySet().removeIf(entry -> entry.getCount() == 1);
78
79 throw new CatalogException("Column name conflict: " + duplicates);
80 }
81
82 comment = (comment == null || comment.isEmpty()) ? eventStream.toString() : comment;
83
84
85 return CatalogTable.of(schema, comment, Lists.newArrayList(), tableOptions);
86 }
87
88 private EventTableUtils() {
89 }
90 }