-
Notifications
You must be signed in to change notification settings - Fork 184
/
Copy pathEnumCodec.java
214 lines (174 loc) · 7.88 KB
/
EnumCodec.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
/*
* Copyright 2020 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 io.r2dbc.postgresql.codec;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.r2dbc.postgresql.client.Parameter;
import io.r2dbc.postgresql.extension.CodecRegistrar;
import io.r2dbc.postgresql.message.Format;
import io.r2dbc.postgresql.util.Assert;
import io.r2dbc.postgresql.util.ByteBufUtils;
import reactor.core.publisher.Mono;
import reactor.util.Logger;
import reactor.util.Loggers;
import reactor.util.annotation.Nullable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static io.r2dbc.postgresql.client.Parameter.NULL_VALUE;
import static io.r2dbc.postgresql.message.Format.FORMAT_TEXT;
/**
* Codec to map Postgres {@code enumerated} types to Java {@link Enum} values.
* This codec uses {@link Enum#name()} to map Postgres enum values as these are represented as string values.
* <p>Note that enum values are case-sensitive.
*
* @param <T> enum type
* @since 0.8.4
*/
public final class EnumCodec<T extends Enum<T>> implements Codec<T> {
private static final Logger logger = Loggers.getLogger(EnumCodec.class);
private final ByteBufAllocator byteBufAllocator;
private final Class<T> type;
private final int oid;
public EnumCodec(ByteBufAllocator byteBufAllocator, Class<T> type, int oid) {
this.byteBufAllocator = Assert.requireNonNull(byteBufAllocator, "byteBufAllocator must not be null");
this.type = Assert.requireNonNull(type, "type must not be null");
this.oid = oid;
}
@Override
public boolean canDecode(int dataType, Format format, Class<?> type) {
Assert.requireNonNull(type, "type must not be null");
return type.isAssignableFrom(this.type) && dataType == this.oid;
}
@Override
public boolean canEncode(Object value) {
Assert.requireNonNull(value, "value must not be null");
return this.type.isInstance(value);
}
@Override
public boolean canEncodeNull(Class<?> type) {
Assert.requireNonNull(type, "type must not be null");
return this.type.equals(type);
}
@Override
public T decode(@Nullable ByteBuf buffer, int dataType, Format format, Class<? extends T> type) {
if (buffer == null) {
return null;
}
return Enum.valueOf(this.type, ByteBufUtils.decode(buffer));
}
@Override
public Parameter encode(Object value) {
Assert.requireNonNull(value, "value must not be null");
return new Parameter(FORMAT_TEXT, this.oid, Mono.fromSupplier(() -> ByteBufUtils.encode(this.byteBufAllocator, this.type.cast(value).name())));
}
@Override
public Parameter encodeNull() {
return new Parameter(Format.FORMAT_BINARY, this.oid, NULL_VALUE);
}
@Override
public Class<?> type() {
return this.type;
}
/**
* Create a new {@link Builder} to build a {@link CodecRegistrar} to dynamically register Postgres {@code enum} types to {@link Enum} values.
*
* @return a new builder.
*/
public static EnumCodec.Builder builder() {
return new Builder();
}
/**
* Builder for {@link CodecRegistrar} to register {@link EnumCodec} for one or more enum type mappings.
*/
public static final class Builder {
private final Map<String, Class<? extends Enum<?>>> mapping = new LinkedHashMap<>();
private RegistrationPriority registrationPriority = RegistrationPriority.LAST;
/**
* Add a Postgres enum type to {@link Enum} mapping.
*
* @param name name of the Postgres enum type
* @param enumClass the corresponding Java type
* @return this {@link Builder}
*/
public Builder withEnum(String name, Class<? extends Enum<?>> enumClass) {
Assert.requireNotEmpty(name, "Postgres type name must not be null");
Assert.requireNonNull(enumClass, "Enum class must not be null");
Assert.isTrue(enumClass.isEnum(), String.format("Enum class %s must be an enum type", enumClass.getName()));
if (this.mapping.containsKey(name)) {
throw new IllegalArgumentException(String.format("Builder contains already a mapping for Postgres type %s", name));
}
if (this.mapping.containsValue(enumClass)) {
throw new IllegalArgumentException(String.format("Builder contains already a mapping for Java type %s", enumClass.getName()));
}
this.mapping.put(name, enumClass);
return this;
}
/**
* Configure the codec registration priority. Default {@link RegistrationPriority#LAST}.
*
* @param registrationPriority the registration priority
* @return this {@link Builder}
* @throws IllegalArgumentException of {@code registrationPriority} is {@code null}.
* @since 0.9
*/
public Builder withRegistrationPriority(RegistrationPriority registrationPriority) {
this.registrationPriority = Assert.requireNonNull(registrationPriority, "registrationPriority must not be null");
return this;
}
/**
* Build a {@link CodecRegistrar} to be used with {@code PostgresqlConnectionConfiguration.Builder#codecRegistrar(CodecRegistrar)}.
* The codec registrar registers the codes to be used as part of the connection setup.
*
* @return a new {@link CodecRegistrar}.
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public CodecRegistrar build() {
Map<String, Class<? extends Enum<?>>> mapping = new LinkedHashMap<>(this.mapping);
return (connection, allocator, registry) -> {
List<String> missing = new ArrayList<>(mapping.keySet());
return PostgresTypes.from(connection).lookupTypes(mapping.keySet())
.filter(PostgresTypes.PostgresType::isEnum)
.doOnNext(it -> {
Class<? extends Enum<?>> enumClass = mapping.get(it.getName());
if (enumClass == null) {
logger.warn(String.format("Cannot find Java type for enum type '%s' with oid %d. Known types are: %s", it.getName(), it.getOid(), mapping));
return;
}
missing.remove(it.getName());
logger.debug(String.format("Registering codec for type '%s' with oid %d using Java enum type '%s'", it.getName(), it.getOid(), enumClass.getName()));
if (this.registrationPriority == RegistrationPriority.LAST) {
registry.addLast(new EnumCodec(allocator, enumClass, it.getOid()));
} else {
registry.addFirst(new EnumCodec(allocator, enumClass, it.getOid()));
}
}).doOnComplete(() -> {
if (!missing.isEmpty()) {
logger.warn(String.format("Could not lookup enum types for: %s", missing));
}
}).then();
};
}
/**
* An enumeration of codec registration priorities.
*/
public enum RegistrationPriority {
FIRST,
LAST
}
}
}